【问题标题】:How to select some columns only in Laravel relationship?如何仅在 Laravel 关系中选择某些列?
【发布时间】:2017-03-23 05:18:54
【问题描述】:

我有以下数据库结构:

  • 用户

    • 身份证
    • 姓名
  • 发帖

    • 身份证
    • user_id
    • 标题
    • 内容

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

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

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

如何才能只获取帖子 ID?

【问题讨论】:

  • 友情提示:使用posts 而不是post。你有很多帖子。

标签: php laravel eloquent


【解决方案1】:

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

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;

【讨论】:

    【解决方案2】:

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

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

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

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

    这样你也可以去掉 user_id。

    【讨论】:

      【解决方案3】:

      你可以这样做

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

      【讨论】:

        猜你喜欢
        • 2020-10-15
        • 1970-01-01
        • 1970-01-01
        • 2021-12-24
        • 2012-08-08
        • 2021-01-13
        • 2019-04-18
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多