【问题标题】:Laravel - Insert a model multiple timesLaravel - 多次插入模型
【发布时间】:2015-01-13 11:00:23
【问题描述】:

我有一个模型,我更改了一些我想插入的属性,但是 Eloquent,在我使用 save() 方法时第一次 save() 之后会自动进行更新,这是我的代码:

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
}

【问题讨论】:

标签: php laravel model eloquent


【解决方案1】:

您可以使用create

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

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

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

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

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;
}

【讨论】:

    【解决方案2】:

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

    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
    }
    

    我不确定您的模型名称是什么,但在这种情况下我使用了 Product。将此替换为您的模型名称。

    【讨论】:

    • 这个模型有很多属性的问题,所以我正在寻找一种方法来改变一些attr并保存
    • 我不太清楚你的意思。您能否更详细地或以其他方式解释它。
    猜你喜欢
    • 2014-08-09
    • 1970-01-01
    • 1970-01-01
    • 2014-07-12
    • 1970-01-01
    • 2013-03-26
    • 2014-12-08
    • 1970-01-01
    • 2015-02-23
    相关资源
    最近更新 更多