将laravel形态集合转换为模型集合?

问题描述 投票:0回答:1

我有3个型号:

[PostLikeTrending

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

laravel laravel-5.8
1个回答
0
投票

您应始终定义关系的反面:

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');

但不会获得帖子模型列表,但数组将帖子表示为键值对

© www.soinside.com 2019 - 2024. All rights reserved.