问题是你正在打电话delete()
在集合上,它没有该方法。
您在这里有几个选择。
模特活动
如果您有事件侦听器deleting
/deleted
模型事件,您需要确保以加载每个模型然后删除的方式进行删除。
在这种情况下,您可以使用destroy
模型上采用 id 列表的方法。它将为每个 id 加载一个新模型,然后调用delete()
在上面。正如您在评论中提到的,它不会将删除限制为仅组织中的那些产品,因此您需要在将列表传递到destroy()
method.
public function destroy($id)
{
try {
$ids = explode(",", $id);
// intersect the product ids for the org with those passed in
$orgIds = array_intersect($org->products()->lists('id'), $ids);
// now this will only destroy ids associated with the org
\App\Product::destroy($orgIds);
}
catch(...) {
}
}
如果您不特别喜欢这种方法,您将需要迭代您的组织产品集合并调用delete()
分别对他们进行。您可以使用标准foreach
,或者您可以使用each
集合上的方法:
public function destroy($id)
{
try {
$ids = explode(",", $id);
$org->products()->find($ids)->each(function ($product, $key) {
$product->delete();
});
}
catch(...) {
}
}
无模型事件
现在,如果您没有需要侦听的任何模型事件,事情就会变得容易一些。在这种情况下,您只需调用delete()
在查询生成器上,它将直接删除记录而不加载任何模型对象。因此,您可以获得更清晰的代码和更好的性能:
public function destroy($id)
{
try {
$ids = explode(",", $id);
// call delete on the query builder (no get())
$org->products()->whereIn('id', $ids)->delete();
}
catch(...) {
}
}