Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/295.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 按相关表值排序(包括不存在关系的元素)_Php_Sorting_Eloquent_Slim 3 - Fatal编程技术网

Php 按相关表值排序(包括不存在关系的元素)

Php 按相关表值排序(包括不存在关系的元素),php,sorting,eloquent,slim-3,Php,Sorting,Eloquent,Slim 3,假设我有两个表:用户和组织 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'

假设我有两个表:用户和组织

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)的组织,我的问题是:我是否可以修改此查询以在没有适当用户连接的情况下也返回值?

您需要一个带有附加联接子句的左联接,以便获得所有组织,若要对结果进行排序,可以使用条件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 );

您的预期输出是什么?您想要所有用户,无论类型是否为1,但先用类型1对用户进行排序,然后再对其他用户进行排序?我希望始终接收按用户(类型1,已删除0)名称排序的所有组织,但当组织没有适当的用户附加到它时,它应该将用户名模拟为空字符串。谢谢!我对你的代码做了一点修改(fe。第一次加入是不必要的),但它可以工作!