Php 在Laravel中使用多个条件联接
我正在尝试使用多个条件连接两个表。由于第二个联接条件,以下查询不起作用Php 在Laravel中使用多个条件联接,php,laravel,Php,Laravel,我正在尝试使用多个条件连接两个表。由于第二个联接条件,以下查询不起作用 $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) ->
$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();
您需要关键字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();
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();
但是,只有当连接是内部连接时,这才可以正常工作,在您的情况下,这是正确的。
添加多个联接子句的正确方法如下
$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();
只需使用此表。SQLSTATE[42000]:语法错误或访问冲突:1066非唯一表/别名:“c”您可以尝试编辑的表吗。由于别名在上一个表中相同,因此输出将有冗余数据,因为您要加入表两次,每次都使用不同的列。可能存在重复项,您收到的错误消息是什么?