【问题标题】:join with multiple conditions in Laravel在 Laravel 中加入多个条件
【发布时间】:2020-02-10 05:14:49
【问题描述】:

我正在尝试使用多个条件连接两个表。由于第二个连接条件,以下查询不起作用。

 $all_update = DB::table('posts as p')
      ->join('cprefs as c','p.qatype', '=', 'c.qatype')
      ->where('c.wwide', '=', 'p.wwide') //second join condition
      ->where('c.user_id', $u_id)
      ->where('p.arank', 1)
      ->get();

【问题讨论】:

标签: php laravel


【解决方案1】:

where() 函数期望最后一个参数是您传入列名的参数。
要比较两列,您应该使用whereColumn 方法。

考虑到这一点,您还可以编写如下代码:

$all_update = DB::table('posts as p') 
 ->join('cprefs as c','p.qatype', '=', 'c.qatype')
 ->whereColumn('c.wwide', '=', 'p.wwide') //second join condition
 ->where('c.user_id', $u_id) 
 ->where('p.arank', 1) 
 ->get();

但是,只有当连接是 INNER JOIN 时,这才能正常工作,这在您的情况下是正确的。
添加多个join子句的正确方法如下

$all_update = DB::table('posts as p') 
->join('cprefs as c', function($q) {
    $q->on('p.qatype', '=', 'c.qatype')
       ->on('c.wwide', '=', 'p.wwide'); //second join condition
}) 
->where('c.user_id', $u_id) 
->where('p.arank', 1) 
->get();

就用这个吧。

【讨论】:

    【解决方案2】:

    您需要关键字 join 才能使用多个连接条件。与表无关。

     $all_update = DB::table('posts as p')
      ->join('cprefs as c','p.qatype', '=', 'c.qatype')
      ->join('cprefs as c2','p.wwide', '=', 'c2.wwide') //second join condition
      ->where('c.user_id', $u_id)
      ->where('p.arank', 1)
      ->get();
    

    【讨论】:

    • SQLSTATE[42000]:语法错误或访问冲突:1066 不是唯一的表/别名:'c'
    • 你可以试试编辑的那个。因为别名与前一个相同
    • 输出会有多余的数据,因为你要加入表两次,每次都有不同的列。
    猜你喜欢
    • 1970-01-01
    • 2013-07-22
    • 2017-07-12
    • 2011-03-02
    • 1970-01-01
    • 2016-03-06
    • 2013-04-06
    • 1970-01-01
    相关资源
    最近更新 更多