简体   繁体   中英

Laravel query orderBy pivot table value

I have a trouble that I can't resolve.

I have two models User & Orgs They are bounded by a pivot table user_org through a belongsToMany relationship. An user can be member of many Orgs and an Orgs can have many users.

Into my controller I craft a query : $users = User::query();

I wanted to get $users depending on various filters, no problem to apply filters, then order them by orgs if they have one "VIP" orgs through some weighting with orderByRaw("CASE WHEN org_id = X THEN 1 ELSE 2 END")

[EDIT] Full query over here :

$users = User::query();
$queryOrder = "CASE WHEN org_id = 13 THEN 1 "; 
$queryOrder .= "WHEN org_id = 14 THEN 2 "; 
$queryOrder .= "ELSE 3 END"; 

$users = $users->join('user_org', 'user_org.user_id', '=', 'users.id')->orderByRaw($queryOrder);

Adding distinct() didn't do the job.

Problem, the result of the query give me some duplicate as an user can belongs to severals orgs. I can't manage to sort the users giving me firstly the users who belongs to the VIP orgs.

Did you have any clue for me ?

Thanks a lot !

What about adding a distinct clause ?

$users = User::query(...)->distinct()->get();

Just FYI, this question reminds me a recent Laracon talk . He used 'orderBySub'. This could be an alternative for you.

Finally I've managed by problem differently. Because the distinct is not working due to the inner join, the order are lost in the better case.

So I've made a "score" computed column in order to group by user_id and max(score).

Here is the request :

            $users = $users->join(
                    DB::raw("(select id, score from (
                                select user_id as id, MAX(CASE WHEN org_id = 13 THEN 5 WHEN org_id = 14 THEN 4 ELSE 0 END) as score 
                                FROM `user_org`
                                group by user_id
                                order by score DESC
                                ) as x)
                            as d"), function($join){
                    $join->on("d.id","=","users.id");
            });

Thanks for the answer and the help ! Cheers

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM