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