我有 3 个模型:
发布
、赞
、热搜
点赞模型和热模型是多态的,都是:
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');
但这不会获得帖子列表模型,而是数组将帖子表示为键值对
关于laravel - 将 laravel 变形集合转换为模型集合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62187740/