php 推流时如何返回空集合

brc7rcf0  于 2023-05-21  发布在  PHP
关注(0)|答案(1)|浏览(181)

下面的代码有问题。当在集合内部执行推送时,当两个条件都为false时,我有一个带有空集合的项。

$admins = collect(new User);
$owner = collect(new User);

if (config('personal.mailing_technician')) {
    $owner = $event->ticket->ownedBy;
}

if (config('personal.mailing_admin')) {
    $admins = User::query()->role('admin')->get();
}

$sentTo = $admins->push($owner);

if ($senTo->isNotEmpty()) {
    .......
}

如果两个条件都为假,我该怎么做才能使它为空?

xxls0lw8

xxls0lw81#

要确保$sentTo在两个条件都为false时是空集合...

$admins = collect(new User);
$owner = collect(new User);

if (config('personal.mailing_technician')) {
    $owner = $event->ticket->ownedBy;
}

if (config('personal.mailing_admin')) {
    $admins = User::query()->role('admin')->get();
}

$sentTo = collect(); // Initialize an empty collection

if ($admins->isNotEmpty() || $owner->isNotEmpty()) {
    $sentTo = $admins->push($owner);
}

if ($sentTo->isNotEmpty()) {
    // Do something
}

相关问题