[英]Laravel 5 - get query builder results grouped by column
For example, I have query: 例如,我有查询:
$posts = DB::table('posts')->select(['id', 'user_id', 'title'])->get();
Then $posts
array looks like this: 然后$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"
}
}
As you can see user with id 1000
have 1 post, user with id 2000
have 2 posts. 如您所见, id 1000
用户有1个帖子, id 2000
用户有2个帖子。
I'd like to get results as associative array with user_id
as keys: 我想以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"
}
}
}
Is there any nice Laravel solution to perform this? 是否有任何不错的Laravel解决方案来执行此操作?
You might want to look into Eloquent Relationships instead of using the Query Builder. 您可能要研究雄辩的关系,而不是使用查询生成器。 In your case you have a one-to-many relationship. 在您的情况下,您具有一对多关系。 So you'd have a User
model that looks something like this: 因此,您将拥有一个类似于以下内容的User
模型:
class User extends Model {
public function posts()
{
// One User can have many Posts
return $this->hasMany('App\Post');
}
}
And a Post
model: 和Post
模型:
class Post extends Model {
public function user()
{
// A Post belongs to one User
return $this->belongsTo('App\User');
}
}
Then you can just get posts by user like this: 然后,您可以像这样按用户获取帖子:
$users = User::all();
foreach ($users as $user)
{
$posts = $user->posts;
// $posts will now contain a Collection of Post models
}
Laravel has no method to do this. Laravel没有办法做到这一点。 But you can do this manually by using this function: 但是您可以使用以下功能手动执行此操作:
public static function makeAssocArrByField($arr, $field)
{
$assocArr = array();
foreach($arr as $arrObj)
{
if(isset($arrObj[$field]))
$assocArr[$arrObj[$field]] = $arrObj;
}
return $assocArr;
}
call method as: 调用方法为:
$posts = makeAssocArrByField($posts, 'user_id');
This will return array as per your required format. 这将根据您所需的格式返回数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.