Laravel 5.2 - 左加入DB :: Raw不工作?

时间:2017-06-27 19:31:20

标签: php mysql json laravel-5.2 laravel-eloquent

我有以下查询,我尝试使用DB::Raw()进行左连接,但我收到错误:

  

缺少Illuminate \ Database \ Query \ Builder :: leftJoin()

的参数2

这是我的疑问:

return $this->model->from('alerts as a')
    ->leftJoin(DB::Raw("locations as l on l.id = JSON_UNQUOTE(JSON_EXTRACT(a.criteria, '$.locationId'))"))
    ->leftJoin(DB::Raw("industries as i on find_in_set(i.id, JSON_UNQUOTE(JSON_EXTRACT(a.criteria, '$.industries')))"))
    ->where('user_id', '=', $userId)
    ->selectRaw("a.id
        , a.name
        , a.criteria
        , GROUP_CONCAT(DISTINCT(i.name) SEPARATOR ', ') as 'Industries'
            ->groupBy('a.id')
            ->orderBy('a.created_at', 'desc');

1 个答案:

答案 0 :(得分:2)

leftJoin函数声明如下:

 public function leftJoin($table, $first, $operator = null, $second = null)

您希望将原始函数作为第二列传递:

return $this->model->from('alerts as a')
                   ->leftJoin('locations AS l', 'l.id', '=', DB::Raw("JSON_UNQUOTE(JSON_EXTRACT(a.criteria, '$.locationId'))"))
                   ->leftJoin('industries as i', function($join){
                        $join->on(DB::raw("find_in_set(i.id, JSON_UNQUOTE(JSON_EXTRACT(a.criteria,  '$.industries')))",DB::raw(''),DB::raw(''))); 
                   })

                   ->where('user_id', '=', $userId)
                   ->selectRaw("a.id
                             , a.name
                             , a.criteria
                             , GROUP_CONCAT(DISTINCT(i.name) SEPARATOR ', ') as 'Industries'")
                   ->groupBy('a.id')
                   ->orderBy('a.created_at', 'desc');

find_in_set建议来自here

我不确定'$.locationId'是什么,但是如果它是变量,你可以将它作为参数传递给DB::raw()函数中的第二个参数。