Laravel select * where id =(select id )

24.5k views Asked by At

Using Laravel eloquent how do I make a query like this:

 select * from branches where user_id =(select id from users where name ='sara' )
5

There are 5 answers

0
Rwd On BEST ANSWER

Assuming that you have a user relationship in your Branch model you could use whereHas:

$branches = Branch::whereHas('user', function ($query) {

    $query->where('name', 'sara');

})->get();

Update

If you're using v8.57.0 or above, you can now use the whereRelation() method instead:

Branch::whereRelation('user', 'name', 'sara')->get();
0
MartinLeitgeb On

I would split it into two queries. First getting the id, then getting the list. Expecting your models to be called "User" and "Branches"

$user = User::where('name', 'sara');
$id = $user->id;
$branches = Branch::where('id', $id);

This site may help you Link

0
Kuldeep Mishra On
 $id = Users::select('id')->where('name','sara')->first();
 $barnches = branches::where('id',$id)->get();

Here Users and branches are models , first is using for 1 row and get for many rows

0
Zayn Ali On

Try this.

$name = 'sara';

$results = BranchModel::whereIn("user_id", function ($query) use ($name) {
    $query->select("id")
        ->from((new UserModel)->getTable())
        ->where("name", $name);
})->get();
0
Yuri On

You can use this:

$users = User::whereName("sara")->get()->pluck('id');
Branch::whereIn('user_id',$users)->get();