0

I have following function in Category model:

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();
}

to fetch news by Category id, now, I also want to fetch news writer which is in the news_author table.

How can I get news author with my function getNewsByCategory?

2 Answers2

0

In News Modal add $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;
}

Mohamed Sakr
  • 1
  • 1
  • 1
0

why not just to add the writer relation inside the with([ ... ]) according to laravel doc

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();
}

Check similar post

4givN
  • 2,936
  • 2
  • 22
  • 51