从集合中移除集合

Remove a collection from a collection

我一直在为我的 Laravel 应用程序构建自定义票证系统,用户可以在他们的票证上发表评论。

放置新评论时,我想向参与工单的每个人发送通知。

满足以下条件的用户可以参与:

为此,我创建了一个用户集合,然后遍历他们以通知他们。唯一的问题是它目前也包括发表评论的人,并且不需要通知他们,因为他们是发表评论的人。

如果 ID 与当前登录的用户匹配,我已尝试filter 删除该集合,但这似乎不起作用:

$ticket = App\Ticket::findOrFail(1);

//Create collection to hold users to be notified
$toBeNotified = collect();

//Add the ticket owner
$toBeNotified->push($ticket->owner);

//If an agent is assigned to the ticket, add them
if(!is_null($ticket->assigned_to)) $toBeNotified->push($ticket->agent);

//Add any active participants that have been invited
$ticket->activeParticipants()->each(function($participant) use ($toBeNotified) {
    $toBeNotified->push($participant->user);
});

//Remove any duplicate users that appear
$toBeNotified = $toBeNotified->unique();

//Remove the logged in user from the collection
$toBeNotified->filter(function($user) {
    return $user->id != Auth::user()->id;
});

//...loop through each user and notify them

进一步阅读后,我认为这是因为您使用 filter 从集合中删除元素,而不是从集合中删除元素。

如果用户是当前登录的用户,我如何从集合中删除他们?

当我在运行上面dd($toBeNotified)之后,结果是这样的:

您可以使用 except 来实现。

$toBeNotified = $toBeNotified->except(auth()->id());

附带说明一下,当您要添加多个用户时应该使用合并。

$toBeNotified = $toBeNotified->merge($ticket->activeParticipants);

您使用的过滤方法也是正确的,但是returns过滤后的collection,同时保持原始collection不变。

$toBeNotified = $toBeNotified->filter(function($user) {
    return $user->id != auth()->id();
});

编辑:except 只有在您有 eloquent collection 时才有效。