在Laravel中查询关系内部的关系雄辩

在Laravel中查询关系内部的关系雄辩,laravel,laravel-relations,Laravel,Laravel Relations,我想根据过去的日期得到一位作家的消息。到目前为止,我已经编写了以下函数: public static function getNewsByAuthorByDate($id, $year, $limit = 1){ return User::where('id', $id)->has('news') ->with(['news' => function($q) use(&$limit, &$year) { $q->whe

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

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();
}
但是
新闻[]
为空。是否可以根据日期获取作家新闻,或者我必须尝试其他方法?

您可以使用

若要使用限值进行快速加载,您应根据以下要求使用软件包

约束紧急加载时,可能不使用
limit
take
查询生成器方法

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

returnuser::with(['news'=>函数($q)use($year){
$q->whereYear('created_at',$year)->latest();
}])
->查找($id);

谢谢,但返回的是相同的。@Gaurav您是否也使用了推荐的软件包?因为上面的语法应该是有效的。@KurtFriars只是为了检查一下,我试着删除了
limit
news[]
仍然是空的。@Gaurav你能试着在没有任何约束的情况下加载关系吗?这样行吗?如果不是,我假设您定义关系的方式存在问题。@KurtFriars我删除了whereYear,我正在
新闻
中获取数据。但假设我想在
title
列中写where子句。可能吗?
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();
}