【问题标题】:Laravel 5.2 - Left Join DB::Raw not working?Laravel 5.2 - 左连接 DB::Raw 不起作用?
【发布时间】:2017-06-27 19:31:19
【问题描述】:

我有以下查询,我尝试使用 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');

【问题讨论】:

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


    【解决方案1】:

    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() 函数的第二个参数传递。

    【讨论】:

    • 我收到错误:Not enough arguments for the on clause
    • 改用->leftJoin('industries as i', DB::raw("find_in_set(i.id, JSON_UNQUOTE(JSON_EXTRACT(a.criteria, '$.industries')))")。假设算子和秒可以消除。
    • 现在我得到:'`` where recruiter_id = 附近的语法错误?在第 5 行按a.ida.created_at desc' 分组(SQL:选择 a.id、a.name、a.criteria、GROUP_CONCAT(DISTINCT(i.name) SEPARATOR ', ') as 'Industries' from alerts as a left join locations as l on l.id = JSON_UNQUOTE(JSON_EXTRACT(a.criteria, '$.locationId')) left join @ 987654340@ as i on find_in_set(i.id, JSON_UNQUOTE(JSON_EXTRACT(a.criteria, '$.industries'))) `` 其中user_id = 1 group by a.id order by @987654345 @.created_at desc)
    • 似乎在where 子句附近搞砸了。
    • 做以下工作:->leftJoin('industries as i', DB::raw("find_in_set(i.id, JSON_UNQUOTE(JSON_EXTRACT(a.criteria, '$.industries')))"), DB::raw(''),DB::raw(''))
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-16
    • 2015-12-02
    • 2018-10-24
    • 2017-05-22
    • 2012-09-10
    相关资源
    最近更新 更多