How to write query builder in laravel to search by timestamp - laravel

SELECT itemid,COUNT(itemid),itemname FROM `items`
WHERE DATE(`save_at`) ='2015-12-16'
GROUP BY itemid
Anyone know how to write this sql in laravel 5 using query builder ???
this is the code i used but it didn't work for me
$query = DB::table('items')
->select(itemid, DB::raw('COUNT(itemid) as noitems')),itemname)
->where( DATE(`save_at`),'=', 2015-12-16)
->group_by('itemid')
->get();

Check the below code.
$query = DB::table('items')
->select(itemid, DB::raw('COUNT(itemid) as noitems')),itemname)
->where( DB::raw('DATE(`save_at`)'),'=', '2015-12-16')
->groupBy('itemid')
->get();

Related

how to convert sql to query builder laravel

Can anyone help me out to convert this SQL to query builder!
SELECT topwords.*,
mw.word AS my_word
FROM topwords
LEFT JOIN (SELECT DISTINCT words.word
FROM definition_word
JOIN words
ON words.id = definition_word.word_id
WHERE definition_word.user_id = $user) AS mw
ON topwords.word = mw.word
I have a problem with how to use a subquery in leftjoin!
I tried something like this but it has error!
See error as image
DB::table('topwords')
->leftJoin(DB::raw("SELECT DISTINCT
words.word
FROM definition_word
JOIN words ON words.id = definition_word.word_id
WHERE definition_word.user_id = $user as mw"),"topwords.word", "=", "mw.word" )
->select(
"topwords.*",
"mw.word AS my_word"
)->orderBy('id','desc')->paginate(15);
you can use Join Sub query official document subquery-joins
$mw = DB::table('words')
->select('DISTINCT words.word')
->join('definition_word', function($join) use ($user)
{
$join->on('wordss.id', '=', 'definition_word.word_id')
->where('definition_word.user_id', $user);
});
$topwords = DB::table('topwords')
->joinSub($mw, 'mw',function ($join) {
$join->on('topwords.word', '=', 'mw.word');
})
->select('topwords.*','mw.word AS my_word')
->orderBy('id','desc')
->paginate(15);
You have this error because of paginate and aggregation
Try to make custom pagination, using LengthAwarePaginator
Here is example: Laracast
So you need to make something like this:
$query = DB::table('topwords')
->leftJoin(DB::raw("SELECT DISTINCT
words.word
FROM definition_word
JOIN words ON words.id = definition_word.word_id
WHERE definition_word.user_id = $user as mw"),"topwords.word", "=", "mw.word" )
->select(
"topwords.*",
"mw.word AS my_word"
);
$paginator = new LengthAwarePaginator($query->get(), $query->count(), $request->input('per_page', 15), $request->input('page', 1));
And then you can use it in the collection

How to make query at laravel

I have sql like this
SELECT no_po FROM tpo_suppheader WHERE no_po not in (
SELECT no_po FROM tpo_supp_stok ).
How to code at laravel?
$datas = DB::table ('tpo_suppheader')
->join('tpo_suppdetil', 'tpo_suppheader.no_po', '=', 'tpo_suppdetil.no_po')
->join('tmsupplier', 'tpo_suppheader.suppid', '=', 'tmsupplier.id')
->select('tpo_suppheader.*', 'tpo_suppdetil.*', 'tmsupplier.nama_supp')
->where('tpo_suppheader.no_po','like',"%".$var_cari."%")
->whereNotIn('no_po', $data_dtl)
->get();
$datas = DB::table ('tpo_suppheader')
->join('tpo_suppdetil', 'tpo_suppheader.no_po', '=', 'tpo_suppdetil.no_po')
->join('tmsupplier', 'tpo_suppheader.suppid', '=', 'tmsupplier.id')
->select('tpo_suppheader.*', 'tpo_suppdetil.*', 'tmsupplier.nama_supp')
->where('tpo_suppheader.no_po','like',"%".$var_cari."%")
->whereNotIn('no_po', $data_dtl)
->get();
This will work for every query: use toSql() to know how the builder translates a query.
For example:
dd(DB::table('table1')->...->toSql());
will dump the translated query. Tinker with this until you get the desired result. Using this method of trial and error, I got this:
$query = DB::table('tpo_suppheader')->select('no_po') # SELECT no_po FROM tpo_suppheader
->whereNotIn('no_po', function ($subquery) { # WHERE no_po NOT IN (
$subquery->select('no_po')->from('tpo_supp_stok'); # SELECT no_po FROM tpo_supp_stok
}); # )
dd($query->toSql());
# "select "no_po" from "tpo_suppheader" where "no_po" not in (select "no_po" from "tpo_supp_stok")"
$results = $query->get();

How can i write nested query in laravel

SELECT * FROM posts WHERE user_id IN (SELECT following FROM follows WHERE user_id='1'
This is the query i want to wirte in laravel to fetch the data how can i write this in laravel
This should work:
$result = DB::table('posts')
->whereIn('user_id', function ($query) {
$query->select('following')
->from('follows')
->where('user_id', 1);
})->get();

Laravel distinct on join results not working in query builder

I have a posts table that has join query with 4 other tables. 3 of them are one to one relations but the 4th is one to many. I want the query to return only 1 row for each post. What i am trying so far is like this-
$query = DB::table('posts')
->select('posts.*',
'subcategories.subcategory_title_en',
'subcategories.subcategory_title_bn',
'categories.category_title_en',
'categories.category_title_bn',
'users.*',
'postimages.postimage_thumbnail'
)
->join('subcategories', 'subcategories.subcategory_id', '=', 'posts.subcategory_id')
->join('categories', 'categories.category_id', '=', 'subcategories.parent_category_id')
->join('users', 'users.id', '=', 'posts.user_id')
->join('postimages', 'postimages.post_id', '=', 'posts.post_id');
$query->groupBy('posts.post_id');
echo $query->count();
exit();
I have currently 50 posts in database, but the query returns all rows for each postimages, more than 1 row for each post that is. I thought distinct would only show each post_id once? What am i missing here?
I would prefer if someone tells me how to do this with query builder. As this will have a lot of searching on different columns and i want it to be as fast as possible.
This is a simpler version -
$query = DB::table('posts')
->select('posts.*','postimages.postimage_thumbnail')
->join('postimages', 'postimages.post_id', '=', 'posts.post_id')
->groupBy('posts.post_id');
echo $query->count();
exit();
The strange thing is the SQL query that is shown by laravel " select posts.*, postimages.postimage_thumbnail from posts inner join postimages on postimages.post_id = posts.post_id group by posts.post_id" works fine in mysql
You should use groupby
Try this code
$query = DB::table('posts')
->select('posts.*',
'subcategories.subcategory_title_en',
'subcategories.subcategory_title_bn',
'categories.category_title_en',
'categories.category_title_bn',
'users.*',
'postimages.postimage_thumbnail'
)
->join('subcategories', 'subcategories.subcategory_id', '=', 'posts.subcategory_id')
->join('categories', 'categories.category_id', '=', 'subcategories.parent_category_id')
->join('users', 'users.id', '=', 'posts.user_id')
->join('postimages', 'postimages.post_id', '=', 'posts.post_id')->groupBy('posts.post_id');
In config/database.php at "mysql" change : 'strict' => true, to false

Laravel pagination not working with group by clause

It seems Laravel pagination does not working properly with group by clause. For example:
$users = Subject::select(DB::raw('subjects.*, count(user_subjects.id) as total_users'))
->join('user_subjects', 'user_subjects.subject_id', '=', 'subjects.id')
->whereNull('user_subjects.deleted_at')
->groupBy('subjects.id')
->orderBy('subjects.updated_at', 'desc')
->paginate(25);
Produced
select subjects.*, count(user_subjects.id) as total_users
from `subjects` inner join `user_subjects` on `user_subjects`.`subject_id` = `subjects`.`id`
where `subjects`.`deleted_at` is null and `user_subjects`.`deleted_at` is null
group by `subjects`.`id`
order by `subjects`.`updated_at` desc
note that, there is no limit clause on the query.
Working fine if no group by clause in the query:
$users = Subject::select(DB::raw('subjects.*, count(user_subjects.id) as total_users'))
->join('user_subjects', 'user_subjects.subject_id', '=', 'subjects.id')
->whereNull('user_subjects.deleted_at')
->orderBy('subjects.updated_at', 'desc')
->paginate(25);
produced the following query:
select subjects.*, count(user_subjects.id) as total_users from `subjects`
inner join `user_subjects` on `user_subjects`.`subject_id` = `subjects`.`id`
where `subjects`.`deleted_at` is null and `user_subjects`.`deleted_at` is null
order by `subjects`.`updated_at` desc
limit 25 offset 0
does anyone has any idea how can i fix this?
Check the documentation
https://laravel.com/docs/5.2/pagination
Currently, pagination operations that use a groupBy statement cannot
be executed efficiently by Laravel. If you need to use a groupBy with
a paginated result set, it is recommended that you query the database
and create a paginator manually.
I know it is an old question, by I am sharing my solution for future reference.
I managed to write a function based on this link which does the heavy job of determining the pagination of a complex query. Just pass the 'QueryBuilder' and it will return the paginated object/collection.
Additionally, this procedure can track and maintain the other parameters except for page=.
public function mergeQueryPaginate(\Illuminate\Database\Eloquent\Builder $query): \Illuminate\Pagination\LengthAwarePaginator
{
$raw_query = $query;
$totalCount = $raw_query->get()->count();
$perPage = request('per-page', 10);
$page = request('page', 1);
$skip = $perPage * ($page - 1);
$raw_query = $raw_query->take($perPage)->skip($skip);
$parameters = request()->getQueryString();
$parameters = preg_replace('/&page(=[^&]*)?|^page(=[^&]*)?&?/', '', $parameters);
$path = url(request()->getPathInfo() . '?' . $parameters);
$rows = $raw_query->get();
$paginator = new LengthAwarePaginator($rows, $totalCount, $perPage, $page);
$paginator = $paginator->withPath($path);
return $paginator;
}
This works for me in laravel 5.2
Select(\DB::RAW("assignment_descendant_child.assignment_descendant_child_id, assignment_descendant_child.assignment_descendant_child_name, COUNT(assignment_descendant.assignment_descendant_id) as xNum"))
->leftJoin(
'assignment_descendant',
'assignment_descendant.assignment_descendant_child_id',
'=',
'assignment_descendant_child.assignment_descendant_child_id'
)
->orderBy('assignment_descendant_child_name')
->groupBy('assignment_descendant_child.assignment_descendant_child_id')
->paginate(\Config::get('constants.paginate_org_index'))
create a database view namedvw_anything. MySql query will be like
create view vw_anything as select subjects.*, count(user_subjects.id) as total_users from subjects inner join user_subjects on user_subjects.subject_id = subjects.id
where subjects.deleted_at is null and user_subjects.deleted_at is null group by subjects.id;
Now create a new model named UserSubModel for this view, protected $table = 'vw_anything';
Now your paginate query will be like UserSubModel::orderBy('subjects.updated_at', 'desc')->paginate(25);
.
To answer this questioin Laravel Pagination group by year and month only
View query will be :
create view vw_anything as select gallery.*, DATE_FORMAT(created_at, "%Y-%m") as tanggal,count(created_at) as jumlah from gallery group by tanggal;
Let you model is VwModel then your paginate query will be
VwModel::where('type','Foto')->orderBy('tanggal','desc')->paginate(2);
This works if you want to group by and paginate.
$code = DB::table('sources')
->select(DB::raw('sources.id_code,sources.title,avg(point) point'))
->join('rating','sources.id_code','rating.id_code')
->groupBy('sources.id_code')
->groupBy('sources.title')
->groupBy('sources.language')
->groupBy('sources.visited')
->paginate(5);

Resources