I have a table name "warga" , the table consist:
id (primary key), no_card, name, description. The no_card is a group from some id.
Then, I will count the description based on no_card.
This is the SQL code :
-SQL code :
SELECT description, COUNT(description) as cnt
FROM ( SELECT distinct no_card, description FROM `warga` ) as t
GROUP by description ;
the SQL already show the data that I need, then in the laravels :
$data = DB::table('warga')->selectRaw('description , COUNT(description ) AS CountData')
->select('no_card', 'description')->distinct()->from('warga')
->groupby('description')
->get();
When I run the program, the alis table CountData is not detected,
Do you have suggestion to fix it?
Thank you,
You can use subquery tables as closures or passing them as builder objects.
DB::table(Closure, alias) or DB::query()->from(Closure, alias)
DB::table(Builder, alias) or DB::query()->from(Closure, alias)
$subquery = DB::table('warga')
->select('no_card', 'description')
->distinct();
$results = DB::table($subquery, 't')
->select('description')
->selectRaw('count(description) as cnt')
->groupBy('description')
->get();
$results = DB::table(function ($query) {
$query->from('warga')
->select('no_card', 'description')
->distinct();
}, 't')
->select('description')
->selectRaw('count(description) as cnt')
->groupBy('description')
->get();
You can even make the query look very SQL-like if you want.
$query = DB::query()
->select('description')
->selectRaw('count(description) as cnt')
->from(function ($sub) {
$sub->select('no_card', 'description')
->distinct();
}, 't')
->groupBy('description')
->get();
Related
I am quite new to Laravel... I have a posts table that has a relation with articles and users tables. In the controller I either get all the posts matching a search criteria or get all posts. In both cases, I learned how to add the related fields to the collection $posts.
// get all posts matching criteria
if (request('search') && request('search') != '') {
$posts = Post::orderBy($orderBySortField,$sortOrder)
->with(['user:id,name','article:id,title'])
->where('post','like','%'.request('search').'%')
->join('users', 'posts.user_id', '=', 'users.id')
->orWhere('users.name','like','%'.request('search').'%')
->join('articles', 'posts.article_id', '=', 'articles.id')
->orWhere('articles.title','like','%'.request('search').'%')
->get();
// get all posts
} else {
$posts = Post::orderBy($orderBySortField,$sortOrder)
->with(['user:id,name','article:id,title'])
->get();
}
// add related fields
foreach ($posts as $post) {
$post->title = '['.$post->article->title.']';
$post->user = '['.$post->user->name.']';
}
When I get all the posts, the related fields are correct in the list displayed in the view page.
However, if I search for the name of a specific user, I get a list where the $posts->user are incorrectly related.
I could figured that by displaying the last queries.
For all the posts:
select * from `posts` order by `posts`.`id` desc
select `id`, `name` from `users` where `users`.`id` in (1, 11)
select `id`, `title` from `articles` where `articles`.`id` in (1)
For the posts written by user 'paul' (user_id = 1):
select * from `posts` inner join `users` on `posts`.`user_id` = `users`.`id` inner join `articles` on `posts`.`article_id` = `articles`.`id` where `post` like ? or `users`.`name` like ? or `articles`.`title` like ? order by `posts`.`id` desc [where ? = %paul% %paul% %paul% ]
select `id`, `name` from `users` where `users`.`id` in (11)
select `id`, `title` from `articles` where `articles`.`id` in (1)
So why is Laravel last queries look for user_id = 11 which is another user?
Am I doing something wrong?
Change the join code the whereHas
// get all posts matching criteria
if (request('search') && request('search') != '') {
$search = request('search');
$posts = Post::orderBy($orderBySortField,$sortOrder)
->with(['user:id,name','article:id,title'])
->where('post','like','%'.$search.'%')
->orWhereHas('user', function($userQuery) use($search){
$userQuery->Where('users.name','like','%'.$search.'%');
})
->orWhereHas('article', function($articleQuery) use($search){
$articleQuery->Where('articles.title','like','%'.$search.'%');
})
->get();
}
If you have define model relation, you don't have to use join in your query, just use with function.
Using the two create duplicate data, that why you getting incorrectly related error.
I'm struggling with Eloquent with query on relation.
For example, I'm looking for only the client John who doesn't have transaction.
How can I do this with Eloquent?
Client model relation
public function transactions()
{
return $this->hasMany(Transaction::class);
}
$results = Client::whereDoesntHave('transactions', function ($query) use ($inputFirst, $period) {
$query->where('transactions.period_id', '=', $period->id)
->where('firstname', '=', $inputFirst);
})
->orderBy('id', 'desc')
->get();
A little help would be great.
Thanks
The issue with your code is that you are nesting the statements. The way you are doing Laravel is generating a SQL like this:
select * from `clients` where not exists
(select * from `transactions`
where `clients`.`id` = `transactions`.`client_id`
and `name` = John)
But the actual SQL code you're looking for is:
select * from `clients` where not exists
(select * from `transactions`
where `clients`.`id` = `transactions`.`client_id`)
and `name` = John)
For that your code should be:
$results = Client::whereDoesntHave('transactions')
->where('firstname', '=', $inputFirst)
->orderBy('id', 'desc')
->get();
*I didn't include the transactions.period_id, coz I wasn't sure if where you're looking to have it. But if it's meant to be inside the second select, leave in the nested statement, if not leave outside.
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
I have a function to get a pass a language number to get language categories record for API purpose. I use a database query statement to select categories table and join the category language table to get category id, parent_id and name (specified language). When execute return error and select the underlying SQL converted the language value to string (e.g. languages_id = 1). I google a lot and no ideas what's wrong. Can anyone advise how to resolve. Thanks a lot.
I tried to copy the underlying SQL to MySQL Workbench and remove the languages_id = 1 --> languages_id = 1 can working properly. I guess the 1 caused error.
Code Sample:
private function getCategories($language) {
$categories = DB::table('categories')
->select(DB::raw('categories.id, categories.parent_id, categories_translation.name'))
->join('categories_translation', function($join) use ($language) {
$join->on('categories_translation.categories_id', '=', 'categories.id');
$join->on('categories_translation.languages_id', '=', $language);
})
->where([
['parent_id' ,'=', '0'],
['categories.id', '=', $id]
])
->get();
return $categories;
}
Error return the converted SQL:
"SQLSTATE[42S22]: Column not found: 1054 Unknown column '1' in 'on
clause' (SQL: select categories.id, categories.parent_id,
categories_translation.name from categories inner join
categories_translation on categories_translation.categories_id =
categories.id and categories_translation.languages_id = 1
where (parent_id = 0 and categories.id = 1))"
You are trying to join using a comparison to an scalar value, instead of a column. I think you actually want to put that comparison as a "where" condition, rather than a "join on"
->where([
['parent_id' ,'=', '0'],
['categories.id', '=', $id],
['categories_translation.languages_id', '=', $language]
])
there is another thing i just discover with your code. when joining table, you are suppose to be joining 'categories_translation.languages_id' with another table id field. in your case, it is not so. you are not joining 'categories_translation.languages_id' with any table field. so ideally, what you are going to do is this
private function getCategories($language) {
$categories = DB::table('categories')
->select(DB::raw('categories.id, categories.parent_id, categories_translation.name'))
->join('categories_translation', function($join) use ($language) {
$join->on('categories_translation.categories_id', '=', 'categories.id');
})
->where([
['parent_id' ,'=', '0'],
['categories.id', '=', $id]
['categories_translation.languages_id', '=', $language]
])
->get();
return $categories;
}
hope this helps
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);