Tuesday, February 28, 2017

Laravel: Querying if a relationship exists

I have a model Foo that contains a hasMany relationship to Bar.

I have a query similar to the following:

$r = Foo::with(['bar' => function($query) {
    $query->where('someProp', '=', 10);
})->get()

However, I want to only return the Foo object if item has a Bar object that satisfies the query.

I'm aware that you can do something like this:

$r = Foo::has('bar')
    ->with(['bar' => function($query) {
        $query->where('someProp', '=', 10);
    })->get();

But that checks if any bar items exists. Not if a bar item exists with someProp = 10

The closest I have got to a solution is this:

$r = Foo::has('bar')
    ->whereHas('bar', function ($query) {
         $query->where('someProp', '=', 10);
    })
    ->with(['bar' => function($query) {
        $query->where('someProp', '=', 10);
    })->get();

But it's clearly not a very nice solution and is probably quite inefficient as I am repeating queries.

How can I solve this issue?




via Yahya Uddin

Advertisement