Get all related articles from this article using active download

I want to get all related articles of a specific article by category.

I have a connection between ArticleandCategory

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

}
+4
source share
2 answers

You can also use whereHas()it if you want to just get related articles:

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

If you want to load everything into one collection:

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

If you want the category model to always strive to load its articles out of the box, you can add

protected $with = ['articles'];

to the Category.php file.

With this you could just use $ article-> category

, , Article.php

protected $with = ['category'];

,

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

. .

+1

Source: https://habr.com/ru/post/1692907/


All Articles