我有一个多态模型,名为 FeedItem ,它与 Alert 和 Publication 模型有多态关系 .
还有另一个名为 Category 的模型, Alert
和 Publication
模型与 hasMany
有关系 .
FeedItem
public function feedable()
{
return $this->morphTo();
}
Publication
public function feedItem()
{
return $this->morphOne('FeedItem', 'feedable');
}
public function categories()
{
return $this->hasMany(Category::class);
}
Alert
public function feedItem()
{
return $this->morphOne('FeedItem', 'feedable');
}
public function categories()
{
return $this->hasMany(Category::class);
}
我希望能够得到所有 feedable
feedable
型号给定的 category
.
我试过了:
$items = FeedItem::with(['feedable.categories' => function($item) {
$item->whereHas('feedable.categories', function ($q) {
$q->where('categories.name', 'my-category');
})->orderBy('id', 'desc')
->paginate();
但是,问题是 feedable
关系永远不会被急切加载,这会阻止 categories
关系的范围被执行 .
例如,如果我这样做:
$items = FeedItem::with(['feedable.categories' => function($item) {
dd('This should be displayed');
$item->whereHas('feedable.categories', function ($q) {
$q->where('categories.name', 'my-category');
})->orderBy('id', 'desc')
->paginate();
永远不会调用 dd()
语句 .
任何人都可以提供这种查询的方式吗?