php – Laravel – Eager加载多对多,只获取一条记录(不是一个集合)

php – Laravel – Eager加载多对多,只获取一条记录(不是一个集合),第1张

概述我的帖子有图像(多对多,因为图像也可以有其他关系).在我的数据透视表中,我有一个名为’featured’的布尔字段,用于指定该帖子的主图像.我想在帖子索引页面中显示与当前用户关联的所有帖子.我只想从数据库中获取一个图像,这应该是特色图像.目前我只能将精选图像作为一个集合.这样做的原因是,如果用户有很多帖子我不想继续并检索所有帖子的特色图片(N 1),而是使用热切加载获得仅2个查询的特色图像. \\ 我的帖子有图像(多对多,因为图像也可以有其他关系).在我的数据透视表中,我有一个名为’featured’的布尔字段,用于指定该帖子的主图像.我想在帖子索引页面中显示与当前用户关联的所有帖子.我只想从数据库中获取一个图像,这应该是特色图像.目前我只能将精选图像作为一个集合.这样做的原因是,如果用户有很多帖子我不想继续并检索所有帖子的特色图片(N 1),而是使用热切加载获得仅2个查询的特色图像.

\Post Modelpublic 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 Illuminate\Database\query\Builder::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)问题.

总结

以上是内存溢出为你收集整理的php – Laravel – Eager加载多对多,只获取一条记录(不是一个集合)全部内容,希望文章能够帮你解决php – Laravel – Eager加载多对多,只获取一条记录(不是一个集合)所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1246326.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-07
下一篇 2022-06-07

发表评论

登录后才能评论

评论列表(0条)

保存