\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加载多对多,只获取一条记录(不是一个集合)所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)