php – Laravel – Eager加载多对多,只获取一条记录(不是一个集
发布时间:2020-12-14 19:36:59 所属栏目:大数据 来源:网络整理
导读:我的帖子有图像(多对多,因为图像也可以有其他关系).在我的数据透视表中,我有一个名为’featured’的布尔字段,用于指定该帖子的主图像.我想在帖子索引页面中显示与当前用户关联的所有帖子.我只想从数据库中获取一个图像,这应该是特色图像.目前我只能将精选图
我的帖子有图像(多对多,因为图像也可以有其他关系).在我的数据透视表中,我有一个名为’featured’的布尔字段,用于指定该帖子的主图像.我想在帖子索引页面中显示与当前用户关联的所有帖子.我只想从数据库中获取一个图像,这应该是特色图像.目前我只能将精选图像作为一个集合.这样做的原因是,如果用户有很多帖子我不想继续并检索所有帖子的特色图片(N 1),而是使用热切加载获得仅2个查询的特色图像.
Post Model public function images() { return $this->belongsToMany(Image::class); } public function image(){ return $this->images()->where('featured','=',true)->first(); } public function featured_image(){ return $this->images()->where('featured',true); } Controller $user = Auth::user(); $posts = $user->posts()->with('image')->get(); // throws error //Call to undefined method IlluminateDatabaseQueryBuilder::addEagerConstraints() // if I do this $posts = $user->posts()->with('featured_image')->get(); // I get all the user's posts,I get the featured image but as a collection even if I only have one record there 我怎样才能做到这一点? 解决方法
可能它不是最好的选择,但如果你只限于两个查询,你可以做下一个:
$posts = $user->posts; $idOfPosts = $posts->pluck('id'); $featuredImages = Image::whereIn('post_id',$idOfPosts)->where('featured',true)->get(); 这不是Eager Load aprroach,而是解决(N 1)问题. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |