繁体   English   中英

Yii2 - 模型在Yii2中不保存在foreach循环中

[英]Yii2 - Model is not saving in foreach loop in Yii2

我有一个变量

我为每个项目运行了foreach循环

$tags = ['#first_Tag','#second_tag','#third_tag','#fourth_Tag'];
foreach ($tags as $t) :

  $model = new Tags;

  $model->tag_name = $t;

  $model->save(); //yii2

endforeach;

此函数仅保存#fourth_Tag的最后一项。 任何人都可以解决这个问题。 提前致谢。

试试这个..

$tags = ['#first_Tag','#second_tag','#third_tag','#fourth_Tag'];
$model = new Tags;

foreach ($tags as $t) :

  $model->id = NULL; //primary key(auto increment id) id
  $model->isNewRecord = true;
  $model->tag_name = $t;

  $model->save(); //yii2

endforeach;

我遇到了完全相同的问题并获得了完美的解 这是经过测试的。

$tags = ['#first_Tag','#second_tag','#third_tag','#fourth_Tag'];
foreach ($tags as $t) :

  $model = new Tags;

  $model->tag_name = $t;

  $model->save(); //yii2

  unset($model);

endforeach;

这是当您创建一个与现有变量具有相同名称的新变量时,它会覆盖其值。 在这里,您不需要创建新属性或将id设置为null ; foreach循环结束之前只是unset() $model

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM