我有3个型号:
[Post
,Like
,Trending
like和趋势模型是多态的,两者都是:
public function likeable()
{
return $this->morphTo();
}
public function trendingable()
{
return $this->morphTo();
}
当我根据喜欢填充趋势表时,访问趋势集合中“帖子”的唯一方法是进行如下的foreach循环:
$chart = Trending::all();
foreach($chart as $chartItem)
{
$chartItem->trendingable->title
}
如何在没有foreach循环的情况下将$chart
集合转换为posts
集合?我正在使用Laravel 5.8
您应始终定义关系的反面:
public Post extends Model
{
public function trendings()
{
return $this->morphMany('App\Trending', 'trendingable');
}
}
现在是否要获取所有具有趋势及其趋势的帖子:
$postWithTrending=Post::with('trendings')->whereHas('trendings')->get();
如果您必须通过趋势模型来获取它们:
$chart = Trending::where('trendingable_model','=',Post::class)->with
('trendingable')->get()->pluck('trendingable');
但不会获得帖子模型列表,但数组将帖子表示为键值对