I'm looking for a way to aggregate a collection of eloquent users pairs in Laravel. [[user][partner]]
I've got the following users table structure
[id] [name] [partner_id]
A user entity has matching partner_ids or null (if no partner exists)
| id | name | partner_id |
+----+---------------+------------+
| 1 | John Doe | 3 |
| 2 | J Random User | NULL |
| 3 | Jane Doe | 1 |
| .. | ... | ... |
Expected result:
[
[
{ "id": 1, "name": "John Doe", "partner_id": 3 },
{ "id": 3, "name": "Jane Doe", "partner_id": 1 },
],
[
{ "id": 2, "name": "J Random User", "partner_id": null },
]
]
I don't get how I fetch the users once and aggregate the $users-collection into pairs in my controller.
<?php
namespace App\Http\Controllers;
use App\User;
class PairController extends Controller
{
public function index()
{
$users = User::all();
$collection = collect();
foreach ($users as $user) {
$myself = $user->id;
$partner = $user->partner_id;
// ... ???
}
return $collection->unique();
}
}
Can anyone help me out with a solution? I'm stuck in my brain.