Php 拉威尔雄辩地收集成对的物品
我正在寻找一种方法来聚合Laravel中的Php 拉威尔雄辩地收集成对的物品,php,laravel,aggregate,Php,Laravel,Aggregate,我正在寻找一种方法来聚合Laravel中的雄辩的用户对集合[[用户][合作伙伴]] 我有下面的users表结构 [id] [name] [partner_id] 用户实体具有匹配的合作伙伴ID或null(如果不存在合作伙伴) 预期结果: [ [ { "id": 1, "name": "John Doe", "partner_id": 3 }, { "id": 3, "name": "Jane Doe", "partner_id": 1 }, ], [ { "
雄辩的
用户对集合<代码>[[用户][合作伙伴]]
我有下面的users表结构
[id] [name] [partner_id]
用户实体具有匹配的合作伙伴ID或null(如果不存在合作伙伴)
预期结果:
[
[
{ "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 },
]
]
我不知道如何在控制器中一次性获取用户并将$users
-集合聚合成成对
<?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();
}
}
试试这个,它并不完美,但可能是一个开始
// Return all users and group them by their id
$grouped_users = User::all()->groupBy('id');
// Now loop through each user on record
User::all()->each(function ($user) use (&$grouped_users) {
if ($user->partner_id && $grouped_users->has($user->partner_id)) {
$partner_id = $user->partner_id;
// Push the user model into our grouped collection
$grouped_users[$partner_id]->push($user);
// Remove the id for the current user from the collection
$grouped_users->forget($user->id);
}
});
请尝试下面的代码
public function index()
{
$usersWithoutPartner = collect();
$usersWithPartner = collect();
User::chunk(100, function ($users) use ($usersWithoutPartner, $usersWithPartner) {
foreach ($users as $user) {
if ($user->partner_id == null) {
$usersWithoutPartner->push($user);
} else {
$usersWithPartner->push($user);
}
}
});
$finalCollection = collect();
$finalCollection->push($usersWithoutPartner);
$finalCollection->push($usersWithPartner);
return $finalCollection;
}
分块是个好主意!可能需要使用和将您的收藏包括在内,以便将它们写入
public function index()
{
$usersWithoutPartner = collect();
$usersWithPartner = collect();
User::chunk(100, function ($users) use ($usersWithoutPartner, $usersWithPartner) {
foreach ($users as $user) {
if ($user->partner_id == null) {
$usersWithoutPartner->push($user);
} else {
$usersWithPartner->push($user);
}
}
});
$finalCollection = collect();
$finalCollection->push($usersWithoutPartner);
$finalCollection->push($usersWithPartner);
return $finalCollection;
}