0

I'm trying to join two tables using more than one condition. The following query is not working because of the second join condition.

 $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();
2

2 Answers 2

2

The where() functions expects the last parameter to be a parameter where as you are passing in a column name.
To compare two columns you should use the whereColumn method.

With that in mind, you could also write your code like below:

$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();

However, this would only work properly if the the join is an INNER JOIN which is true in your case.
The correct method to add multiple join clauses is as below

$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();

Just use this one.

Sign up to request clarification or add additional context in comments.

Comments

0

You need the keyword join to use multiple join condition. Irrespective of table.

 $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();

3 Comments

SQLSTATE[42000]: Syntax error or access violation: 1066 Not unique table/alias: 'c'
can you try the edited one. as the alias name were same in the previous one
The output will have redundant data, because you are joining the table two times, each time with a different column.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.