gpt4 book ai didi

php - Yii $this->save() 和 $this->commit() 在循环中使用时仅保存最后一条记录

转载 作者:行者123 更新时间:2023-11-29 08:06:17 24 4
gpt4 key购买 nike

我试图通过 Yii 中的模型将多条记录插入到我的数据库中。我使用 foreach 将数据从 Controller 传递到模型。首先检查数据库中是否存在该字段,如果结果为假,则插入数据库。但是,插入时,它不会插入第一条记录,而是插入从 Controller 末尾传递的记录。但一旦第一个数据传递到 Controller ,就会生成一个 Id。

我的 Controller :

foreach($user_likes['data'] as $ul){
$category_id = $categoriesModel->ifCategoryExists($ul['category']);
if(!$category_id){
$category_id = $categoriesModel->add($ul['category']);
$categories[$category_id] = $ul['category'];
}
}

我的模型:

public function add($params = '') {
$transaction = $this->dbConnection->beginTransaction();
try {
$this->Category = $params;
$this->save();
$transaction->commit();
echo "{ inserted_id ", $this->Id," },{ inserted_category ",$params," }<br/>";
return $this->Id;
} catch (Exception $e) {
$transaction->rollback();
throw $e;
}
}

当我看到 echo 的输出

{ inserted_id 17 },{ inserted_category Community }
{ inserted_id 17 },{ inserted_category Local business }
{ inserted_id 17 },{ inserted_category Actor/director }
{ inserted_id 17 },{ inserted_category Event planning/event services }
{ inserted_id 17 },{ inserted_category Album }
{ inserted_id 17 },{ inserted_category Magazine }
{ inserted_id 17 },{ inserted_category Internet/software }
{ inserted_id 17 },{ inserted_category Consulting/business services }
{ inserted_id 17 },{ inserted_category Education website }
{ inserted_id 17 },{ inserted_category Author }
{ inserted_id 17 },{ inserted_category Public figure }
{ inserted_id 17 },{ inserted_category Business person }
{ inserted_id 17 },{ inserted_category Public figure }
{ inserted_id 17 },{ inserted_category Community }
{ inserted_id 17 },{ inserted_category Comedian }
{ inserted_id 17 },{ inserted_category Business person }
{ inserted_id 17 },{ inserted_category Public figure }
{ inserted_id 17 },{ inserted_category News personality }
{ inserted_id 17 },{ inserted_category Political organization }
{ inserted_id 17 },{ inserted_category Computers/technology }
{ inserted_id 17 },{ inserted_category Travel/leisure }
{ inserted_id 17 },{ inserted_category Community }

非常奇怪的是,它正在插入

Community

最佳答案

CActiveRecord 有一个状态,它以"new"状态开始(并使用“插入”场景)。一旦你对它调用 save() ,它就不再是新的并进入“更新”场景。 CActiveRecord 不会插入不同的记录,1 个实例 = 1 行。

但是,如果您确实想使用单个实例,只需重置即可:

$this->Id = NULL;
$this->isNewRecord = TRUE;

如果您将其添加到 $this->save() 之前,它应该可以工作。我强烈建议按原样使用该框架并创建新实例。

关于php - Yii $this->save() 和 $this->commit() 在循环中使用时仅保存最后一条记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22680650/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com