简体   繁体   中英

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?

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']);
   }

You need at least user_id to make it work.

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

If you don't want to show it for a particular case; try:

$user->post->each(function($post) {
    $post->setVisible(['id']);
});

That way you can get rid of the user_id too.

To get just a list of ids instead of eloquent models I would go with query builder.

DB::table('posts')
    ->select('posts.id') // fetch just post ID
    ->join('users', 'posts.user_id', '=', 'users.id')
    ->where('users.id', ...) // if you want to get posts only for particular user
    ->get()
    ->pluck('id'); // results in array of ids instead of array of objects with id property

In order for it to work you need to add use DB; in the same file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM