0
我一直在为我的Laravel应用程序构建定制门票系统,用户可以在其门票上放置注释。从集合中删除集合
当发表新评论时,我想向通知门票中涉及的每个人发送通知。
用户可以参与,如果他们是:
- 票证拥有者
- 分配给机票代理
- 邀请作为参与者的车票
要做到这一点,我正在创建一组用户,然后通过它们循环来通知他们。唯一的问题是,它目前还包括发表评论的人,并且他们不需要被通知,因为他们是离开评论的人。
我试图集合如果ID匹配当前登录的用户删除用户,但这似乎并没有工作:
$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()'不起作用,因为它排除了基于集合中的键的项目,并且键与用户的ID无关。如果你首先通过'keyBy()'键入集合的用户id,它会起作用。 – patricus
@patricus我在这个项目中只用了一周'except' https://github.com/gothinkster/laravel-realworld-example-app/blob/master/database/seeds/DummyDataSeeder.php#L111和i肯定知道它的工作原理。我甚至还为你自己写了一个测试。不知道你是否做了这个评论,甚至不费心去测试。检查我更新的答案。 – Sandeesh
@Sandeesh为此感谢。我实现了'merge()'来清理代码,并使用'filter()',但正如你所指出的,我正在改变'$ toBeNotified'来实际设置返回的内容。谢谢您的帮助! – James