GluePear
GluePear

Reputation: 7715

Laravel Eloquent get model by scope on associated model

I have an Eloquent model Foo which has a field bar_id. I define the relationship between them in the Foo model:

public function Bar()
{
    $this->belongsTo('App\Bar');
}

The Bar model has a baz_id, and a scope to get all Bars which have a particular baz_id. This is the scope in my Bar model:

public function scopeFromBaz($query, $bazId)
{
    return $query->where('baz_id', $bazId)
}

I now want to make a call of all Foos where their associated Bar has a baz_id of 1. How do I do this? I've tried:

Foo::where('bar', function($query) {
    $query->fromBaz(1);
});

But that produces the error

Call to undefined method Illuminate\Database\Query\Builder::fromBaz()

Upvotes: 0

Views: 1319

Answers (1)

pseudoanime
pseudoanime

Reputation: 1593

You have to use whereHas when you're adding conditions to relationships.

The query should be

Foo::whereHas('Bar', function ($query) {
    $query->fromBaz(1);
})->get();

See : https://laravel.com/docs/5.6/eloquent-relationships#querying-relationship-existence

I also spotted something on your other piece of code, you haven't added a return on your Bar function in the Foo model.

Upvotes: 2

Related Questions