【问题标题】:How to order records with having a relationship comes last in query result如何排序有关系的记录在查询结果中排在最后
【发布时间】:2021-09-17 18:15:06
【问题描述】:

我有两个名为 callscall_histories 的表。例如,以下是我的查询。

$calls = Call::select([
    'calls.id as id', 'calls.reserved_at', 'calls.app_id',
    'calls.call_type_id', 'call_histories.call_id'
])->leftJoin('call_histories', 'calls.id', '=', 'call_histories.call_id')
    ->whereIn('call_type_id', $callTypesIds)
    ->where(DB::raw("(DATE_FORMAT(reserved_at,'%Y-%m-%d'))"), '<=', 
        Carbon::now()->format('Y-m-d'))
    ->where('app_id', $callAppId)
    ->free()
    ->orderBy('reserved_at')
    ->take(100);

我想知道一个呼叫是否有任何call_histories 订单作为查询结果中的最后一条记录。我该怎么做?

【问题讨论】:

    标签: php mysql laravel laravel-query-builder eloquent-relationship


    【解决方案1】:

    由于call_histories.call_id 如果找不到则为空,您可以按此排序:

    $calls = Call::select([
                'calls.id as id', 'calls.reserved_at', 'calls.app_id', 'calls.call_type_id', 'call_histories.call_id'
            ])->leftJoin('call_histories', 'calls.id', '=', 'call_histories.call_id')
                ->whereIn('call_type_id', $callTypesIds)
                ->where(DB::raw("(DATE_FORMAT(reserved_at,'%Y-%m-%d'))"), '<=', Carbon::now()->format('Y-m-d'))
                ->where('app_id', $callAppId)
                ->free()
                ->orderBy('reserved_at')
                ->orderBy('call_id')
                ->take(100);
    

    【讨论】:

    • 这里有问题。 call 可能没有 call_history,因此 orderBy 不会有 call_id
    • 是和不是。 “no call_id”仅仅意味着它是null。 Null 是一个值,如果你有一个值,你可以排序。
    • 如果记录不存在,那么就没有字段为空!
    • 不在记录本身中,而是在加入的结果集中!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-25
    • 2023-03-06
    • 1970-01-01
    • 1970-01-01
    • 2012-04-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多