雄辩的关系从表中检索所有行

时间:2019-12-31 00:43:00

标签: php laravel eloquent

我有2个模型:PostImage。每个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;

它带给我所有帖子,而不是特定的帖子,如下所示:

Return when try to access the relation from a specific instance

但是,当我使用以下语法返回时:

$post->with(['images'])->where('id', $post->id)->get();

Return using 'where' method

它可以正常工作,但是第一种方法应该也可以,不是吗?

2 个答案:

答案 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);