yii 學習筆記值 如何批量像數據庫插入數據

轉載地址: http://blog.sina.com.cn/s/blog_3eba8f1c0102vahy.html

由於不知道怎麼轉載 ,所以直接把地址複製到這裏 ,如果原作者不允許,我會直接刪除掉的。


在開發中遇到過這樣問題,foreach循環插入數據時,表中只插入了循環的最後一條數據,而其它數據沒有真實添加,追蹤發現,內存地址中循環時新一條數據會覆蓋前一條數據,解決辦法是另起一個對象;

如下:


第一種方法

$model = new User();
foreach($data as $attributes)
{
     $_model = clone $model; //克隆對象
     $_model->setAttributes($attributes);
     $_model->save();
}

第二種方法

$model = new User();
foreach($data as $attributes)
{
      $model->isNewRecord = true;
      $model->setAttributes($attributes);
      $model->save() && $model->id=0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章