使用Laravel,我有两个模型,Prize
和Tickets
,每个奖品只能有一张彩票。
在Prizes
上迭代时,我想为每个分配一个唯一的票证。我从集合中随机选择一个,然后在分配后将其从集合中删除。
我注意到在每个each
调用中,但有些奖品具有相同的Ticket ID,我怀疑已经分配的tickets没有在each
循环中从$tickets
中删除。
有人能解释一下为什么会这样,以及我如何正确编码吗?
$prizes = Prize::all()->limit(5)->get();
$tickets = Tickets::all()->limit(5)->get();
// iterate over runner up prizes
$prizes->each(function ($prize, $key) use($tickets) {
// select ticket from bag
$winner = $tickets->random();
// assign to prize
$prize->ticket_winner_id = $winner->id;
// remove id from remainder
$tickets = $tickets->except($winner->id);
});
为什么不尝试在$tickets之前添加一个符号:
$prizes = Prize::all()->limit(5)->get();
$tickets = Tickets::all()->limit(5)->get();
// iterate over runner up prizes
$prizes->each(function ($prize, $key) use(&$tickets) {
// select ticket from bag
$winner = $tickets->random();
// assign to prize
$prize->ticket_winner_id = $winner->id;
// remove id from remainder
$tickets = $tickets->except($winner->id);
});
这就意味着php不需要该变量的副本,而需要对其进行变异