【问题标题】:Laravel 5 - get query builder results grouped by columnLaravel 5 - 获取按列分组的查询生成器结果
【发布时间】:2015-04-03 12:40:29
【问题描述】:

例如,我有查询:

$posts = DB::table('posts')->select(['id', 'user_id', 'title'])->get();

那么$posts数组看起来像这样:

array(3) {
  [0]=>
  object(stdClass) (3) {
    ["id"]=>
    int(1)
    ["user_id"]=>
    int(1000)
    ["title"]=>
    string(8) "Post # 1"
  }
  [1]=>
  object(stdClass) (3) {
    ["id"]=>
    int(2)
    ["user_id"]=>
    int(2000)
    ["title"]=>
    string(8) "Post # 2"
  }
  [2]=>
  object(stdClass) (3) {
    ["id"]=>
    int(3)
    ["user_id"]=>
    int(2000)
    ["title"]=>
    string(8) "Post # 3"
  }
}

如您所见,id 1000 的用户有 1 个帖子,id 2000 的用户有 2 个帖子。

我想将结果作为关联数组以 user_id 为键:

array(2) {
  [1000]=>
  array(1) {
    [0]=>
    object(stdClass) (3) {
      ["id"]=>
      int(1)
      ["user_id"]=>
      int(1000)
      ["title"]=>
      string(8) "Post # 1"
    }
  }
  [2000]=>
  array(2) {
    [1]=>
    object(stdClass) (3) {
      ["id"]=>
      int(2)
      ["user_id"]=>
      int(2000)
      ["title"]=>
      string(8) "Post # 2"
    }
    [2]=>
    object(stdClass) (3) {
      ["id"]=>
      int(3)
      ["user_id"]=>
      int(2000)
      ["title"]=>
      string(8) "Post # 3"
    }
  }
}

有没有很好的 Laravel 解决方案来执行此操作?

【问题讨论】:

    标签: php mysql laravel laravel-5 query-builder


    【解决方案1】:

    您可能想要查看Eloquent Relationships 而不是使用查询生成器。在您的情况下,您有 一对多 关系。所以你会有一个看起来像这样的User 模型:

    class User extends Model {
    
        public function posts()
        {
            // One User can have many Posts
            return $this->hasMany('App\Post');
        }
    
    }
    

    还有一个Post 模型:

    class Post extends Model {
    
        public function user()
        {
            // A Post belongs to one User
            return $this->belongsTo('App\User');
        }
    
    }
    

    然后您可以像这样获取用户的帖子:

    $users = User::all();
    
    foreach ($users as $user)
    {
        $posts = $user->posts;
    
        // $posts will now contain a Collection of Post models
    }
    

    【讨论】:

    • 我绝对应该将现有模型重构为 Eloquent,谢谢!
    【解决方案2】:

    Laravel 没有办法做到这一点。但是您可以使用此功能手动执行此操作:

    public static function makeAssocArrByField($arr, $field)
    {
        $assocArr = array();
        foreach($arr as $arrObj)
        {
            if(isset($arrObj[$field]))
                $assocArr[$arrObj[$field]] = $arrObj;
        }
    
        return $assocArr;
    }
    

    调用方法为:

    $posts = makeAssocArrByField($posts, 'user_id');
    

    这将根据您所需的格式返回数组。

    【讨论】:

      猜你喜欢
      • 2017-05-22
      • 2019-06-22
      • 2020-09-08
      • 2018-03-15
      • 2021-07-08
      • 2018-08-05
      • 2016-11-07
      • 1970-01-01
      • 2014-01-03
      相关资源
      最近更新 更多