Collections 忘记不';行不通
如果我尝试从此集合中删除项目Collections 忘记不';行不通,collections,laravel,Collections,Laravel,如果我尝试从此集合中删除项目 $examples = Example::where('example', '=', $data['example'])->get(); table: examples id example 1 abc 49 bce $examples->find(49); ^^ `example id` 通过做 $examples->forget(20); 它不会从集合中删除该项目,我仍然会取回原来在那里的所有项目
$examples = Example::where('example', '=', $data['example'])->get();
table: examples
id example
1 abc
49 bce
$examples->find(49);
^^ `example id`
通过做
$examples->forget(20);
它不会从集合中删除该项目,我仍然会取回原来在那里的所有项目。我已经阅读了Laravel文档和api文档。(我认为)它应该会起作用,但它不会
有人能指出我做错了什么吗
这仍然返回一个对象
$examples->forget(49);
return $examples->find(49);
还有其他方法,如推送或获取
非常感谢 你犯了一个小错误,实际上你没有注意到。我自己做了:)
忘记
使用数组键
从集合中删除对象项
Array(0 => 'abc'
1 => 'bcd'
49 => 'aaa'
)
$examples->forget(49);
^^ array key 49
其中,find
使用id
从集合中查找对象
$examples = Example::where('example', '=', $data['example'])->get();
table: examples
id example
1 abc
49 bce
$examples->find(49);
^^ `example id`
我只是想补充一下阿南的答案。一旦你有了一个集合,你就可以像这样循环通过它来按ID删除
function forgetById($collection,$id){
foreach($collection as $key => $item){
if($item->id == $id){
$collection->forget($key);
break;
}
}
return $collection;
}
$examples = Example::where('example', '=', $data['example'])->get();
$examples = forgetById($examples,20);
根据文档说明,
forget()
按键工作。“键”这个词是不明确的,因为它们的意思是数组键,也称为“索引”,而不是作为id的模型键
但是,在其他方法中,例如find()
或contains()
中,它们使用单词“key”表示模型键,因此您可以看到混淆
查看源代码时,您可以看到forget()
方法位于illumb\Support\Collection
类中,而不是illumb\Database\Eloquent\Collection
中
我的理论是支持类应该是更通用的,所以它不考虑模型键,但我真的不知道。
$examples->reject(20);
与大多数其他收集方法一样,reject返回一个新的收集实例;它不会修改调用它的集合 谢谢,这的确是个问题。有没有办法通过对象的id轻松“忘记”对象?您可以在Laravel 7中执行拒绝('foo'),即使文档中另有建议。请参阅Ali Baker的回答和我的评论。我正要记下这一点,因为这强烈暗示您需要回调,但事实上,您只需提供一个项名称,它就会将其删除(从新实例中)。当然,回调也能起作用。不能忘记的事情:忘记(),除了()。使用Laravel7.27.Yh进行测试,我想这是很久以前的事了,早在v7.27之前