简体   繁体   English

使用预先加载来获取给定文章中的所有相关文章

[英]Get all related articles from given article using eager loading

I want to get all related articles of particular article based on category. 我想根据类别获取特定文章的所有相关文章。

I have relation between Article and Category 我有ArticleCategory之间的关系

Article.php Article.php

public function category(){

    return $this->belongsTo(ArticleCategory::class,'category_id','id');

}

ArticleCategory.php ArticleCategory.php

 public function articles(){

    return $this->hasMany(Article::class,'category_id','id');

}

ArticleController.php 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'));

}

You can also use whereHas() if you want to just get related articles: 如果你想获得相关文章,你也可以使用whereHas()

$relatedArticles = Article::whereHas('category', function($q) use($article) {
    $q->where('id', $article->category_id);
})
->get();

If you want load everything to one collection: 如果要将所有内容加载到一个集合中:

$relatedArticles = Article::with(['category.articles' => function($q) use($article) {
    $q->where('id', $article->category_id);
}])
->get();

If you wanna have the category model always eager load its articles out of the box, you could add 如果你想让类别模型总是急于加载它的文章开箱即用,你可以添加

protected $with = ['articles'];

to the Category.php file. 到Category.php文件。

With that you then could just use $article->category 有了这个,你就可以使用$ article-> category

This also works for the implicit bindings in a function call, so you could eager load category for every article when you write in Article.php 这也适用于函数调用中的隐式绑定,因此当您在Article.php中写入时,您可以为每篇文章急切加载类别

protected $with = ['category'];

Sadly if you wanna eagerload everything with 可悲的是,如果你想加载所有东西

protected $with = ['category.articles'];

you get an endless loop in this case. 在这种情况下,你会得到一个无限循环。 Just for info for similar cases in the future, you can do nested eager loading with this. 仅用于将来类似案例的信息,您可以使用此方法进行嵌套的预先加载。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM