two columns where clause merge with comma - php

I want to build a query.
here is table:
id user_id sn_no
1 22 00112233
2 22 987654325
3 22 65489732
4 25 984123123
5 25 9568456456
6 25 65456456
I want result like this:
{
"user_id":22,
"sn_no": "00112233,987654325,65489732"
}
{
"user_id":25,
"sn_no": "984123123,9568456456,65456456"
}
Can anyone please help to solve this issue?
I have tried: concat, GROUP_CONCAT but can not get the result.
Can you please help me add this in Join query?
$users = \DB::table('users')
->join('users_mcu', 'users.id', '=', 'users_mcu.user_id')
->join('country_user', 'users.id', '=', 'country_user.user_id')
->join('country_phase_color', 'country_user.country_id', '=', 'country_phase_color.id')
->select('users.id', 'users.first_name', 'users.last_name', 'users.company', 'users.designation', 'users.lang', 'users.phone', 'users.disp_graph', 'users.user_image', 'users.email', 'users.role', 'users.created_at', 'users.updated_at', 'country_user.country_id', 'country_phase_color.country_name')
->get();

Try this-
YourModel::select('user_id')
->selectRaw('GROUP_CONCAT(sn_no) as sn')
->groupBy('user_id')
->get();

Try this.
$data = \DB::table('tablename')->select('user_id', \DB::raw('group_concat(sn_no) as sn_nos'))->groupBy('user_id')->get();
as if you want to change SEPARATOR then you can use SEPARATOR for it otherwise the default will be ','
\DB::table('tablename')->select('user_id',DB::raw("(GROUP_CONCAT(sn_no SEPARATOR '#')) as `sn_nos`"))->groupBy('user_id')->get();

use mysql group_concat function and laravel groupBy and raw function
DB::tabe('tableName')
->select('id','user_id',\DB::raw('GROUP_CONCAT(`sn_no`) as sn_no_t'))
->groupBy('user_id')
->get()

Try this
use DB;
DB::table('tableName')
->select('id','user_id','DB::raw("(GROUP_CONCAT(sn_no SEPARATOR ',')) as `sn_nos`")')
->groupBy('user_id')
->get();

You can try this
Model::select('user_id')
->selectRaw('GROUP_CONCAT(sn_nos) as sn_nos')
->groupBy('user_id')
->get();

Related

Helpe me to convert SQL query to Laravel eloquent

I have this SQL query:
SELECT *, count(*) as mostView FROM users RIGHT JOIN visitors ON users.id = visitors.user_id GROUP BY users.id HAVING users.isActive=1 AND users.fullName IS NOT NULL AND users.photo_id IS NOT NULL AND users.role_id IN(1, 3) ORDER BY mostView DESC LIMIT 5
It works, but I need convert to Laravel eloquent, i'm using laravel 5.6, could any one helpe me thanks in advance
I'm assuming that you have map the relationship in your Model if you do you can do like below,
$userViews = User::->with('vistors')
->where('isActive',1)
->whereNotNull('fullName')
->whereNotNull('photo_id')
->whereIn('role_id ',[1,3])
->get();
$mostView = $userViews->sortBy(function ($collection) {
return $collection->vistors->count()
})->take(5)
hope this helps
Not going to spoon feeding but can provide you some ideas to convert raw sql to eloquent, your sql should ideally be like this:
User::selectRaw('*', 'count(*) as mostView')
->rightJoin()
->groupBy()
->having()
->where // whereNotNull // wherIn
->orderBy()
->take(5)
->get();
Kindly refer to laravel docs: https://laravel.com/docs/5.6/queries
Thanks for all i'm studies Database: Query Builder on the link
https://laravel.com/docs/5.6/queries
and so i solved my question by myself
the answer is:
$mostViews = DB::table('users')
->rightJoin('visitors', 'users.id' , '=' , 'visitors.user_id')
->select('users.*', DB::raw('count(*) as mostView'))
->where('isActive', '=', '1')
->whereNotNull('fullName')
->where('photo_id', '<>', 'NULL')
->where(function ($q){
$q->where('role_id', '=', '1')
->orWhere('role_id', '=', '3');
})
->groupBy('user_id')
->orderBy('mostView', 'desc')->take(5)->get();

Laravel query doesn't want to select last one

I tried distinct before but somehow my query won't select the last comment. He always select the oldest comment. Then i tried it with groupBy instead of distinct. But this won't work either.
My current query:
\App\Comment::limit(5)->groupBy('comments.id')
->orderBy('comments.id', 'desc')
->join('topics', 'comments.topic_id', '=', 'comments.id')
->select('comments.user_id', 'topics.id', 'topics.name')
->whereIn('topics.cat_id', $cats)
->where([['comments.removed', '=', false],['topics.removed', '=', false]])
->get();
It's pretty long.
Hopfully someone can explain me why this won't work.
Errors found so far
groupBy is not needed
Your join statement join('topics', 'comments.topic_id', '=', 'comments.id') should be joining columns in table comments and topics
Fix
\App\Comment::select('comments.user_id', 'topics.id', 'topics.name')
->join('topics', 'comments.topic_id', 'topics.id')
->whereIn('topics.cat_id', $cats)
->where('comments.removed', false)
->where('topics.removed', false)
->latest('comments.id')
->limit(5)
->get();
PS: latest('comments.id') is handy for orderBy('comments.id', 'desc')
UPDATE
To get the latest comment for at most 5 recently updated topics, try this
\App\Comment::select('comments.user_id', 'topics.id', 'topics.name')
->from(DB::raw("(select * from comments where removed = 0 order by id desc) as comments"))
->join('topics', 'comments.topic_id', 'topics.id')
->whereIn('topics.cat_id', $cats)
->where('topics.removed', false)
->groupBy('topics.id')
->limit(5)
->get();
Try to use whereHas. You should do something like this:
\App\Comment::where('removed', false)
->whereHas('topic', function($q) use ($cats) {
$q->where('removed', false)
->whereIn('cat_id', $cats);
})
->limit(5)
->orderBy('id', 'desc')->get();
To achieve this, you must have the relations established by functions, such as topics (ie: hasMany) in Comment model.

Laravel Eloquent - Select MAX with other columns

I'm trying to select a number of columns along with MAX. The raw query would be something like: SELECT users.id, ..., MAX(ur.rank) AS rank but I cannot figure out how to do it using the query builder supplied by Laravel in Eloquent.
This is my attempt:
$user = User::join('users_ranks AS ur', function($join) {
$join ->on('ur.uid', '=', 'users.id');
})
->where('users.id', '=', 7)
->groupBy('users.id')
->first(['users.id', 'users.username', 'MAX(ur.rank) AS rank']);
I simply cannot figure it out. What I want to achieve is I'm selecting a user where users.id = 7, and I'm wanting to select the MAX rank that's in users_ranks where their users_ranks.uid = users.id.
I was told to avoid sub-queries as when working with large result sets, it can slow things down dramatically.
Can anyone point me in the right direction? Thanks.
I think you should rewrite it like this:
DB::table('users')
->select(['users.id', 'users.username', DB::raw('MAX(ur.rank) AS rank')])
->leftJoin('users_ranks AS ur', 'ur.uid', '=', 'users.id')
->where('users.id', '=', 7)
->groupBy('users.id')
->first();
No sense to use User:: if you use table names later and want to fetch not all of the fields ( 'users.id', 'users.username' ).

DISTINCT method using Laravel 5 eloquent query builder

I'm struggling to get unique results when using the DISTINCT method in laravel. This is my query
//Get users that are part of this sector
$users = DB::table('users')->distinct()
->join('projects', 'users.id', '=', 'projects.userID')
->where('projects.sectorID', '=', $sector->sectorID)
->get();
dd($users);
The result shows 3 users with the same ID, when I only want one of them in the results.
How should I change my query?
Try to use group by id
$users = DB::table('users')
->join('projects', 'users.id', '=', 'projects.userID')
->where('projects.sectorID', '=', $sector->sectorID)
->groupBy('users.id')
->get();
dd($users);

Eloquent - join clause with string value rather than column heading

I have a question regarding join clauses in Eloquent, and whether you can join on a string value rather than a table column.
I have the code below querying a nested set joining parent/child records in a table 'destinations' via a table 'taxonomy'.
The second $join statement in the closure is the one causing an issue; Eloquent assumes this is a column, when I would actually just like to join on t1.parent_type = 'Destination' - ie, t1.parent_type should = a string value, Destination.
$result = DB::connection()
->table('destinations AS d1')
->select(array('d1.title AS level1', 'd2.title AS level2'))
->leftJoin('taxonomy AS t1', function($join) {
$join->on('t1.parent_id', '=', 'd1.id');
$join->on('t1.parent_type', '=', 'Destination');
})
->leftJoin('destinations AS d2', 'd2.id', '=', 't1.child_id')
->where('d1.slug', '=', $slug)
->get();
Is it possible to force Eloquent to do this? I've tried replacing 'Destination' with DB::raw('Destination') but this does not work either.
Thanking you kindly.
Another best way to achieve same is :
$result = DB::connection()
->table('destinations AS d1')
->select(array('d1.title AS level1', 'd2.title AS level2'))
->leftJoin('taxonomy AS t1', function($join) {
$join->on('t1.parent_id', '=', 'd1.id');
$join->where('t1.parent_type', '=', 'Destination');
})
->leftJoin('destinations AS d2', 'd2.id', '=', 't1.child_id')
->where('d1.slug', '=', $slug)
->get();
Replace your on with where
try using DB::raw("'Destination'")

Categories