繁体   English   中英

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

[英]Eloquent relations retrieving all rows from table

我有 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;

它给我带来了所有帖子,而不是具体的帖子,如下所示:

尝试从特定实例访问关系时返回

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

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

使用“where”方法返回

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

如果你想通过 post_id 获得一篇文章并且所有图片都属于它,你可以尝试:

$post = Post::with(['images'])->findOrFail($id);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM