Limon Monte
Limon Monte

Reputation: 54459

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:

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.

I'd like to get results as associative array with user_id as keys:

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?

Upvotes: 0

Views: 275

Answers (2)

Bogdan
Bogdan

Reputation: 44586

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:

class User extends Model {

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

}

And a Post model:

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
}

Upvotes: 1

Raviraj Chauhan
Raviraj Chauhan

Reputation: 653

Laravel has no method to do this. 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.

Upvotes: 0

Related Questions