Laravel 5.2 - Left Join DB::Raw not working?

被刻印的时光 ゝ 提交于 2020-05-09 05:58:49

问题


I have the following query where I'm trying to use DB::Raw() for the left join but I'm getting error:

Missing argument 2 for Illuminate\Database\Query\Builder::leftJoin()

This is my query:

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:


The leftJoin function is declared like this:

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

You want to pass your raw functions in as the second column:

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

The find_in_set suggestion came from here.

I'm not sure what '$.locationId' is, but if it's a variable, you can pass that along as a parameter within an array as the second parameter on the DB::raw() function.



来源:https://stackoverflow.com/questions/44788395/laravel-5-2-left-join-dbraw-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!