Lai32290 Lai32290 - 1 month ago 11
PHP Question

How to select some columns only in Laravel relationship?

I have the following database structure:


  • user


    • id

    • name


  • post


    • id

    • user_id

    • title

    • content




So I creating the relationship function in my model:

class User extends Model {
public function post()
{
return $this->hasMany(Post::class);
}
}


If I execute
$user->post
will returning complete post objects.

How to can I get only posts ID?

Answer

You can either do it like this

$user = User::with(['post' => function ($q) {
            $q->select('id');
        }])->where('id', $id)->first();

or you can set select on you relationship

public function post()
   {
      return $this->hasMany(Post::class)->select(['id','user_id']);
   }