简体   繁体   English

Laravel Eloquent在关联模型上按作用域获取模型

[英]Laravel Eloquent get model by scope on associated model

I have an Eloquent model Foo which has a field bar_id . 我有一个雄辩的Foo模型,其中有一个bar_id字段。 I define the relationship between them in the Foo model: 我在Foo模型中定义它们之间的关系:

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

The Bar model has a baz_id , and a scope to get all Bar s which have a particular baz_id . Bar模型具有一个baz_id ,以及一个范围以获取具有特定baz_id所有Bar This is the scope in my Bar model: 这是我的Bar模型的范围:

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

I now want to make a call of all Foo s where their associated Bar has a baz_id of 1 . 我现在想调用所有Foo ,它们关联的Barbaz_id1 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() 调用未定义的方法Illuminate \\ Database \\ Query \\ Builder :: fromBaz()

You have to use whereHas when you're adding conditions to relationships. 向关系中添加条件时,必须使用whereHas。

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 参见: 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. 我还在其他代码上发现了一些东西,但您尚未在Foo模型中的Bar函数上添加任何收益。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM