Laravel - Insert a model multiple times

Sn0*_*opr 0 php model laravel eloquent

I have a model that I change some attributes I want to insert it but Eloquent, after the first save() will automatically do an update while I'm using save() method, here is my code:

for ($i = 0; $i < $range; $i++) {
  $model->attr = "Some new value";
  $model->save(); // after the first save() will do update but I want to an insert
}
Run Code Online (Sandbox Code Playgroud)

luk*_*ter 6

您可以使用 create

$attributes = [
    'foo' => 'bar'
];
for ($i = 0; $i < $range; $i++) {
    $attributes['foo'] = 'bar'.$i;
    Model::create($attributes);
}
Run Code Online (Sandbox Code Playgroud)

或者,如果您想在模型中创建一个函数:

public function saveAsNew(){
    $this->exists = false;
    $this->attributes[$this->primaryKey] = null; // reset the id
    return $this->save();
}
Run Code Online (Sandbox Code Playgroud)

我也写了这个函数,多次保存相同的模型(是的,我知道这不是你的事,但我还是想发布它:

public function saveMultiple($times){
    $saved = true;
    for($i = 0; $i < $times; $i++){
        if(!$this->save()){
            $saved = false;
        }
        $this->attributes[$this->primaryKey] = null; // unset the id
        $this->exists = false;
    }

    return $saved;
}
Run Code Online (Sandbox Code Playgroud)


Koe*_*vel 5

每次循环时都需要创建模型的新实例.试试这个:

for ($i = 0; $i < $range; $i++) {
  $model = new Product;
  $model->attr = "Some new value";
  $model->save(); // after the first save() will do update but I want to an insert
}
Run Code Online (Sandbox Code Playgroud)

我不确定你的模型名称是什么,但我在这个例子中使用了Product.将其替换为您的型号名称.