Home > Software design >  Laravel Advanced Wheres how to implement wheres from different table
Laravel Advanced Wheres how to implement wheres from different table

Time:07-17

So I have two table and this is the column that they have

TableA = id, slug, user_id, friend_id, parent_id

TableB = id, user_id, friend_id

This is my example coding

$tableA = TableA::where('slug', '3')->first();

$tableB = TableB::where( function ($query) use ($tableA) {
    $query->where('user_id', $tableA->user_id);
    $query->where('friend_id', $tableA->friend_id);
    $query->where('tableA.parent_id','=','2');
})->exists();

It seems like only this two where conditions are working

$query - > where('user_id', $tableA - > user_id);
$query - > where('friend_id', $tableA - > friend_id);

The last where conditions didn't work. Anyone know what wrong in my coding

$query - > where('tableA.parent_id', '=', '2');

CodePudding user response:

try with this query

$query->where($tableA->parent_id, '=', '2');

it's because tableA is a variable, not a relation

CodePudding user response:

In last condition you write condition for tableA. It will not work.

You can try this

$tableA = TableA::where('slug', '3')->where('tableA.parent_id','=','2')->first();

$tableB = TableB::where( function ($query) use ($tableA) {
    $query->where('user_id', $tableA->user_id);
    $query->where('friend_id', $tableA->friend_id);
})->exists();

Also I'm recommending you try make this logic with one query, using join or subquery. You can read this

  • Related