2

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?

Gaurav
  • 149
  • 12

2 Answers2

2

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

OMR
  • 11,736
  • 5
  • 20
  • 35
  • Thanks but it returns the same. – Gaurav Jul 13 '20 at 09:12
  • @Gaurav did you use the package recommended as well? Because the above syntax should be working. – Kurt Friars Jul 13 '20 at 09:15
  • @KurtFriars Just to check I tried removing `limit` the `news[]` is still null. – Gaurav Jul 13 '20 at 09:29
  • @Gaurav Can you try just loading the relation without any contraints? Does that work? If not I am assuming there is an issue with the way you have defined your relation. – Kurt Friars Jul 13 '20 at 09:30
  • @KurtFriars I removed whereYear and I am getting data inside `news`. But let's say I want to write where clause in `title` column. Is it possible? – Gaurav Jul 13 '20 at 09:34
  • @Gaurav Forget constraining it for a moment. Does User::where('id', $id)->with(['news'])->first(); return news for a user where you would expect it to? – Kurt Friars Jul 13 '20 at 09:36
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/217731/discussion-between-gaurav-and-kurt-friars). – Gaurav Jul 13 '20 at 09:39
0

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);
Hafez Divandari
  • 8,381
  • 4
  • 46
  • 63