Laravel Eloquent 关系里面的查询关系

Query relationship inside the relationship in Laravel Eloquent

我想根据过去的日期获取一位作家的消息。到目前为止我已经写了函数:

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

但是 news[] 为空。是否可以根据日期获取作家新闻,还是我必须尝试其他方式?

你可以使用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();
}

要使用预加载限制,您应该使用包 eloquent-eager-limit

根据 documentation:

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

此外,您不需要使用has方法,如果用户没有新闻,news将为空:

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