我有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();
它可以正常工作,但是第一种方法应该也可以,不是吗?
答案 0 :(得分:1)
如果您想通过post_id获得一篇帖子,并且所有图片都属于该帖子,则可以尝试:
$post = Post::with(['images'])->findOrFail($id);
答案 1 :(得分:0)
更改模型关系
public function post()
{
return $this->belongsTo('App\Post', 'post_id', 'id');
}
public function images()
{
return $this->hasMany('App\Image', 'post_id', 'id');
}
在您的控制器中
$post = Post::with('images')->findOrFail($id);