Yahya Uddin
Yahya Uddin

Reputation: 28841

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?

Upvotes: 0

Views: 705

Answers (1)

ndberg
ndberg

Reputation: 3971

If the condition is a fix one, you could define another relationship in Foo like this

public function bar_fix()
{
    return $this->hasMany(Bar::class)->where('someProp', 10);
}

And then use this relationship in the query:

$r = Foo::has('bar_fix')->with('bar_fix')->get();

however, this is just usefull if the condition is fix..

Upvotes: 2

Related Questions