php - 使用预先加载从给定文章中获取所有相关文章

标签 php laravel laravel-5 laravel-5.5

我想根据类别获取特定文章的所有相关文章。

我在 ArticleCategory 之间有关系

文章.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/

相关文章:

php - Laravel - 更改 created_at 以使用 unix 时间戳

javascript - 在 React App 中显示文本编辑器中的内容

php - 带重音的记录上带有 "b"前缀的字符串

php - MySQL Laravel ORM 中的日期

javascript - Firebase 安全规则来自特定 Web url 的存储

php - 每次更新到mysql的html表单数组

php - laravel 5.2 中 mysql 的复选框

javascript - 在 Laravel 中安装后如何需要 npm 包?

php - 如何用php检测图像中的形状?

php - 将自定义类添加到主 Blade 模板