I have two models, User
and Post
, where a User
can have multiple Post
models. In my application, I only want to retrieve the title
column from the related Post
model when querying for a User
. Here is my current code:
class User extends Model
{
public function posts()
{
return $this->hasMany(Post::class);
}
}
class Post extends Model
{
public function user()
{
return $this->belongsTo(User::class);
}
}
Here is what I have tried to retrieve the title
column for the related Post
models:
$user = User::with('posts:title')->get();
However, this retrieves all the columns for the Post
model. How can I modify my code to only retrieve the title
column for the related Post
models? Thank you!
2
Answers
If you want to get the data with selected column you also need to pass the
FK
to identify its relationship.The example below tells the the post also need the
user_id
column to identify the relationship betweenPOST
andUSER
modeltry this