Query relationship inside the relationship in Laravel Eloquent

Viewed 91

I am trying to get the news of a writer according to date passed. I have written function so far:

public static function getNewsByAuthorByDate($id, $year, $limit = 1){
    return User::where('id', $id)->has('news')
      ->with(['news' => function($q) use(&$limit, &$year) {
         $q->where('created_at', 'like', '%' . $year . '%')->latest()->limit($limit);
      }])
      ->first();
}

But the news[] is null. Is it possible to get writer news according to date or do I have to try another way?

2 Answers

you can use whereYear

public static function getNewsByAuthorByDate($id, $year, $limit = 1){
    return User::where('id', $id)->has('news')
      ->with(['news' => function($q) use(&$limit, &$year) {
         $q->whereYear('created_at',$year)->latest()->limit($limit);
      }])
      ->first();
}

and to use limit with eager loading you should use the package eloquent-eager-limit

According to the documentation:

The limit and take query builder methods may not be used when constraining eager loads.

Also, You don't need to use has method, the news would be empty if the user has no news:

return User::with(['news' => function($q) use($year) {
         $q->whereYear('created_at', $year)->latest();
      }])
      ->find($id);
Related