skip to Main Content

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


  1. 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 between POST and USER model

    $user = User::with('posts:title,user_id')->get();
    
    Login or Signup to reply.
  2. try this

     $user = User::with(['posts' => function ($query) {
                          $query->select('title');
                  }])->get();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search