如何选择一些列只在Laravel关系


How to select some columns only in Laravel relationship?

我有以下数据库结构:

    用户
    • id
    • <
    • 名称/gh>
    • id
    • user_id
    • 标题

我在模型中创建了关系函数:

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

如果我执行$user->post将返回完整的post对象。

如何只获得帖子ID?

你可以这样做

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

或者你可以选择你的关系

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

您至少需要user_id才能使其工作

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

如果你不想在特定情况下显示它;试一试:

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

这样你也可以去掉user_id

要获取id列表而不是雄辩的模型,我会使用查询生成器。

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

为了使其工作,您需要在同一文件中添加use DB;