I've been trying to fetch only selected columns using laravel relationship. Main tables:
posts
- id
- author_id
- content
post_media
- id
- post_id
- link
- caption
In my laravel Post model, I've defined relationship like,
public function postMedia()
{
return $this->hasMany(PostMedia::class);
}
And while fetching data, the query is:
Post::select('id', 'content')
->with('postMedia:id,link')
->where('author_id', '=', auth()->user()->id)
->paginate();
But the query returns empty post_media array, even after replacing paginate() with get()
I also tried,
Post::select('id', 'content')
->with(['postMedia' => function ($query) {
$query->select('id', 'link')
})
->where('author_id', '=', auth()->user()->id)
->paginate();
But still didn't work. Am I missing something? Thank you.