使用Eloquent更新模型会导致内存不足



我试图用新的描述更新我的项目模型,但是当ConsoleCommand被执行时,它会抛出内存不足。如果我创建一个新的项目模型,就没有问题。我怀疑它试图更新所有记录,而不是我指出的项目。

$items = Item::query()->where('description', '=', '')->get();
foreach ($items as $item) {
    if ($item->exists()) {
        $item->description = "new description";
        $item->save();
   }
}

PHP致命错误:在..vendorilluminatesupportStr.php on line 2710中允许的内存大小为134217728字节已耗尽(试图分配65488字节)

PHP致命错误:在..vendorilluminatesupportStr.php on line 2710中允许的内存大小为134217728字节已耗尽(试图分配65488字节)

count($items) = 3255
count($item) = 1
$items->count() = 3255
$item->count() = 3255

EDIT1:
这个问题关注的是为什么调用$item->save()会导致内存不足。当只有一个模型试图保存/更新时。

EDIT2:
为什么下面的代码仍然会抛出内存不足?

$item = Item::where('description', '=', '')->first();
$item->description = "new description";
$item->save();

,但当使用以下内容代替->save()时不使用

:
Item::where('item_id', '=', $item->item_id)->update($item->toArray());

您正在查询所有项目,这就是您得到错误的原因。这就像将表中的所有数据复制到内存中。如果每行的描述不同,则尝试使用update()方法来逐行更新:

foreach ($data as $row) {
    Item::where('description', 'old description')
        ->update(['description' => 'new desccription']);
}

不要忘记将description添加到$fillable数组。

如果出于某种原因你真的想使用save()而不是update(),你可以使用chunk()方法来加载数据。

使用chunk方法可以在处理大型结果集时节省内存

您可以使用update()函数在单个查询中更新多行:

Item::where('description', '=', '')
    ->update(['description' => 'new description']);

不确定这是否有帮助,但我有完全相同的问题…这是因为被称为"save"的Model I没有主键。

最新更新