Reputation: 41
I have 2 Models: Post
and Image
. Each Image
is associated with a Post
and one Post
can have many Image
s, as its shown below.
public function post()
{
return $this->belongsTo(Post::class, 'id', 'post_id');
}
public function images()
{
return $this->hasMany(Image::class, 'post_id', 'id');
}
But, When I try to retrieve Post with a id:1
it using:
$post = Post::find($id);
$post->images;
It brings me ALL posts, not the specific one, as you can see below:
However, when I return using this syntax:
$post->with(['images'])->where('id', $post->id)->get();
it works fine, but the first method should work as well, shouldn't it?
Upvotes: 1
Views: 65
Reputation: 109
if you want to get one post by post_id and all images belong to it you can try it:
$post = Post::with(['images'])->findOrFail($id);
Upvotes: 1