从特定类别中获取新闻以及拉拉维尔中的每个新闻作者



我在类别模型中有以下功能:

public function news(){
return $this->belongsToMany(News::class,'news_categories','category_id','news_id');
}
public function writer(){
return $this->belongsToMany(NewsAuthor::class,'news_authors','news_id','user_id');
}
public static function getNewsByCategory($id, $limit){
return Category::where('id', $id)->has('news')
->with(['news' => function($q) use(&$limit) {
$q->latest()->limit($limit);
}])->first();
}

按类别 ID 获取新闻,现在,我还想获取news_author表中的新闻作家。

如何使用我的函数getNewsByCategory获取新闻作者?

在新闻模态中添加$with

protected $with = ['writers'];
public function writers(){
return $this->belongsToMany(NewsAuthor::class,'news_authors','news_id','user_id');
}
// you can get writers for each new
foreach($category->news as $new) {
$wirters = $new->writers;
}

为什么不根据 Laravel 文档在with([ ... ])中添加writer关系

public static function getNewsByCategory($id, $limit){
return Category::where('id', $id)->has('news')
->with(['news' => function($q) use(&$limit) {
$q->latest()->limit($limit);
}, 'writer'])->first();
}

查看类似帖子

相关内容

  • 没有找到相关文章

最新更新