Lai32290 Lai32290 - 1 year ago 80
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
will returning complete post objects.

How to can I get only posts ID?

Answer Source

You can either do it like this

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

or you can set select on you relationship

public function post()
      return $this->hasMany(Post::class)->select(['id','user_id']);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download