[英]Eloquent relations retrieving all rows from table
我有 2 个模型: Post
和Image
。 每个Image
与一个Post
相关联,一个Post
可以有多个Image
,如下所示。
public function post()
{
return $this->belongsTo(Post::class, 'id', 'post_id');
}
public function images()
{
return $this->hasMany(Image::class, 'post_id', 'id');
}
但是,当我尝试使用id:1
检索 Post 时,它使用:
$post = Post::find($id);
$post->images;
它给我带来了所有帖子,而不是具体的帖子,如下所示:
但是,当我使用此语法返回时:
$post->with(['images'])->where('id', $post->id)->get();
它工作正常,但第一种方法也应该工作,不是吗?
如果你想通过 post_id 获得一篇文章并且所有图片都属于它,你可以尝试:
$post = Post::with(['images'])->findOrFail($id);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.