将 laravel 变形集合转换为模型集合?
Convert laravel morph collection to model collection?
我有 3 个模型:
Post
、Like
、Trending
点赞和热搜的模特都是多态,都是:
public function likeable()
{
return $this->morphTo();
}
public function trendingable()
{
return $this->morphTo();
}
当我根据喜欢填充趋势 table 时,从趋势集合中访问 "posts" 的唯一方法是像这样创建一个 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();
如果您必须通过 Trending 模型获得它们:
$chart = Trending::where('trendingable_model','=',Post::class)->with
('trendingable')->get()->pluck('trendingable');
但这不会获得帖子列表模型,但数组将帖子表示为键值对
我有 3 个模型:
Post
、Like
、Trending
点赞和热搜的模特都是多态,都是:
public function likeable()
{
return $this->morphTo();
}
public function trendingable()
{
return $this->morphTo();
}
当我根据喜欢填充趋势 table 时,从趋势集合中访问 "posts" 的唯一方法是像这样创建一个 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();
如果您必须通过 Trending 模型获得它们:
$chart = Trending::where('trendingable_model','=',Post::class)->with
('trendingable')->get()->pluck('trendingable');
但这不会获得帖子列表模型,但数组将帖子表示为键值对