我有一个雄辩的模型Foo
有一个字段bar_id
。我在Foo
模型中定义它们之间的关系:
public function Bar()
{
$this->belongsTo('App\Bar');
}
Bar
模型有一个baz_id
,并且范围可以得到所有具有特定Bar
的baz_id
s。这是我的Bar
模型的范围:
public function scopeFromBaz($query, $bazId)
{
return $query->where('baz_id', $bazId)
}
我现在想打电话给所有Foo
s,他们的相关Bar
有baz_id
的1
。我该怎么做呢?我试过了:
Foo::where('bar', function($query) {
$query->fromBaz(1);
});
但这会产生错误
调用未定义的方法Illuminate \ Database \ Query \ Builder :: fromBaz()
当你为关系添加条件时,你必须使用whereHas。
查询应该是
Foo::whereHas('Bar', function ($query) {
$query->fromBaz(1);
})->get();
见:https://laravel.com/docs/5.6/eloquent-relationships#querying-relationship-existence
我还在你的另一段代码上发现了一些东西,你没有在Foo模型中添加Bar函数的回报。