我想根据类别获取特定文章的所有相关文章。
我在 Article
和 Category
之间有关系
文章.php
public function category(){
return $this->belongsTo(ArticleCategory::class,'category_id','id');
}
ArticleCategory.php
public function articles(){
return $this->hasMany(Article::class,'category_id','id');
}
ArticleController.php
public function singleArticle(Article $article){
//I want to convert this statement to eager loading statement
$relatedArticles = $article->category->articles;
return view('pages/article',compact('article','relatedArticles'));
}
最佳答案
如果只想获取相关文章,也可以使用whereHas()
:
$relatedArticles = Article::whereHas('category', function($q) use($article) {
$q->where('id', $article->category_id);
})
->get();
如果您想将所有内容加载到一个集合中:
$relatedArticles = Article::with(['category.articles' => function($q) use($article) {
$q->where('id', $article->category_id);
}])
->get();
关于php - 使用预先加载从给定文章中获取所有相关文章,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48518498/