我有3个模型:帐户 - 合作伙伴 - 用户,其中3个属于belongsToMany关系(account_user,account_partner)。我想过滤所有用户帐户授权的用户合作伙伴。
我已经编写了基本的foreach循环地狱,我想问一些优化这种过滤的技巧(比如逃避n + 1和其他问题)。
$userPartners = [];
foreach (auth()->user()->accounts as $account) {
foreach ($account->partners as $partner) {
$inList = false;
foreach ($userPartners as $userPartner) {
if ($userPartner->id === $partner->id) {
$inList = true;
}
}
if (!$inList) {
$userPartners[] = $partner;
}
}
}
dd($userPartners);
答案 0 :(得分:2)
首先急切加载与load
的关系。这样可以避免N+1
问题:
$user = auth()->user()->load('accounts');
$userPartners = [];
$user->accounts->each(function ($account) use ($userPartners) {
$ids = $account->partners->pluck('id');
if (!in_array($account->id, $ids)) {
$userPartners[] = $account->partners->where('id', $account->id);
}
});
答案 1 :(得分:1)
您可以这样做:
<强> Controller.php这样强>
$userPartners = collect();
auth()->user()->accounts->each(function($account) use ($userPartners) {
$account->partners->each(function($partner) use ($userPartners) {
if(!$userPartners->contains('id', $partner->id)) $userPartners->push($partner);
});
});
dd($userPartners);