对相关表值进行排序(包括没有现有关系的元素)

问题描述 投票:1回答:1

可以说我有两个表:用户和组织

users:
id int,
name varchar,
type int,
deleted bool

organisations:
id int,
name varchar
deleted bool

我想按类型1名称的用户对组织进行排序。我知道当我想按关系值排序时我必须使用join:

$organisationsModel -> join( 'users', 'organisations.id', '=', 'users.organisationId', 'left' ) 
    -> select( 'organisations.*', 'users.name as userName' ) 
    -> where( 'users.type', 1 ) 
    -> where( 'users.deleted', 0 )
    -> orderBy( 'userName', 'ASC );

但它只显示具有类型1的用户(已删除设置为0)的组织,我的问题是:我可以修改此查询以在没有正确用户连接的情况下返回值吗?

php sorting eloquent slim-3
1个回答
1
投票

您需要一个带有其他连接子句的左连接才能获得所有组织。要对结果进行排序,您可以使用条件order by子句

 $organisationsModel->leftJoin('users', function ($join) {
                                    $join->on('organisations.id', '=', 'users.organisationId')
                                         ->where( 'users.type', 1)
                                         ->where( 'users.deleted', 0 );
                    })
                    ->select( 'organisations.*', 'users.name as userName' ) 
                    ->orderByRaw('CASE WHEN users.type = 1 AND users.deleted = 0 THEN 1 ELSE 0 END DESC')
                    ->orderBy( 'userName', 'ASC );

Another similar problem

© www.soinside.com 2019 - 2024. All rights reserved.