【问题标题】:Laravel leftJoin with closure join in relational tableLaravel leftJoin 与关系表中的闭包连接
【发布时间】:2019-02-08 18:20:12
【问题描述】:

表格:

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

动态变量:$salonID

逻辑(文字):

我需要根据 salon_id 和电话参数为特定沙龙接听来自 client_calls 的所有呼叫,在客户端表中通过电话进行左连接以获取客户名称(如果匹配),并且在左连接闭包中执行内部连接通过 clients.id = salon_clients.client_id where user_id = $userID 检查客户是否与该沙龙中的 salon_client 表匹配。

逻辑(代码):

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 + where 条件被简单地传递了。

我错过了什么吗? 再次感谢您的帮助!

【问题讨论】:

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


    【解决方案1】:

    试试这个

    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();
    

    【讨论】:

      猜你喜欢
      • 2019-05-08
      • 1970-01-01
      • 1970-01-01
      • 2021-01-05
      • 1970-01-01
      • 2015-01-27
      • 2021-02-21
      • 1970-01-01
      • 2021-02-28
      相关资源
      最近更新 更多