Newtz
Newtz

Reputation: 41

Eloquent relations retrieving all rows from table

I have 2 Models: Post and Image. Each Image is associated with a Post and one Post can have many Images, 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:

Return when try to access the relation from a specific instance

However, when I return using this syntax:

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

Return using 'where' method

it works fine, but the first method should work as well, shouldn't it?

Upvotes: 1

Views: 65

Answers (1)

LuongPs
LuongPs

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

Related Questions