Laravel通过关系表中的闭包联接离开了联接

时间:2018-09-03 17:19:20

标签: php laravel laravel-5 eloquent laravel-query-builder

表格:

- salon_clients: id, salon_id, client_id
- clients: id, name, phone
- client_calls: id, salon_id, phone

动态变量:$salonID

逻辑(文本):

我需要根据salon_id和电话参数接听来自特定沙龙的client_calls的所有电话,如果有匹配项,请在客户表中通过电话进行leftjoin以获取客户名称,并且在leftjoin闭包中也要进行内部联接通过client.id = salon_clients.client_id检查客户端是否与该沙龙中的salon_client表相匹配。其中user_id = $ userID。

逻辑(代码):

return ClientCall::leftJoin('clients', function($query) use ($salonID){
        $query->on('client_calls.phone', 'clients.phone');

        $query->join('salon_clients', function($query) use ($salonID){
            $query->on('clients.id', 'salon_clients.client_id');
            $query->where('salon_clients.salon_id', $salonID);
        });
    })
    ->where('client_calls.salon_id', $salonID)
    ->orderBy('client_calls.created_at', 'DESC')
    ->select(
        'client_calls.*',
        'clients.name'
    )
    ->get();

返回:

[
    {
        "id": 5,
        "salon_id": 1,
        "phone": "0746707241",
        "type": "missed",
        "created_at": "2018-09-02 10:36:45",
        "updated_at": "2018-09-02 10:39:32",
        "name": 'Test client',
    }
]

问题是测试客户端不属于salon_id 1(在这种情况下,名称应为NULL)。因此,只需简单地传递条件的innerjoin +。

我想念什么吗? 再次感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

尝试

return ClientCall::leftJoin('clients', function($query) use ($salonID){
    $query->on('client_calls.phone', 'clients.phone');
})
->join('salon_clients', function($query) use ($salonID){
        $query->on('clients.id', 'salon_clients.client_id');
        $query->where('salon_clients.salon_id', $salonID);
})
->where('client_calls.salon_id', $salonID)
->orderBy('client_calls.created_at', 'DESC')
->select(
    'client_calls.*',
    'clients.name'
)
->get();