yii\db\Command 无法转换为字符串 - 插入 - Yii2
yii\db\Command could not be converted to string - Insert - Yii2
我正在重构一些包含多个插入查询的代码,为此我正在转换每个插入方法,如下所示:
$code = Yii::$app->db->createCommand()
->insert('code', $codeData
)->execute();
像这样:
$codeQuery = Yii::$app->db->createCommand()
->insert('code', $codeData);
return $codeQuery;
并且在另一个执行交易的方法中:
$transaction = Yii::$app->db->beginTransaction();
try{
Yii::$app->db->createCommand($codeQuery)->execute();
$transaction->commit();
} catch (\Exception $e) {
$transaction->rollBack();
throw $e;
} catch (\Throwable $e) {
$transaction->rollBack();
throw $e;
}
但是我得到了错误:
Object of class yii\db\Command could not be converted to string
这个 post:post 并没有真正帮助我。
我怀疑正确的选择是重写事务方法可以执行的每一个插入命令,还是直接将我当前的插入命令输出转换为可行的东西。
如果您已经分配了 $codeQuery = Yii::$app->db->createCommand()->insert('code', $codeData)
,则无需将 $codeQuery 传递给另一个 createCommand 方法。该方法可以读取sql的字符串作为变量。
如果要将命令转换为字符串,请进行转换:
$str = $codeQuery->getRawSql(); // get sql statement
$res = $codeQuery->execute(); // execute sql statement
我正在重构一些包含多个插入查询的代码,为此我正在转换每个插入方法,如下所示:
$code = Yii::$app->db->createCommand()
->insert('code', $codeData
)->execute();
像这样:
$codeQuery = Yii::$app->db->createCommand()
->insert('code', $codeData);
return $codeQuery;
并且在另一个执行交易的方法中:
$transaction = Yii::$app->db->beginTransaction();
try{
Yii::$app->db->createCommand($codeQuery)->execute();
$transaction->commit();
} catch (\Exception $e) {
$transaction->rollBack();
throw $e;
} catch (\Throwable $e) {
$transaction->rollBack();
throw $e;
}
但是我得到了错误:
Object of class yii\db\Command could not be converted to string
这个 post:post 并没有真正帮助我。
我怀疑正确的选择是重写事务方法可以执行的每一个插入命令,还是直接将我当前的插入命令输出转换为可行的东西。
如果您已经分配了 $codeQuery = Yii::$app->db->createCommand()->insert('code', $codeData)
,则无需将 $codeQuery 传递给另一个 createCommand 方法。该方法可以读取sql的字符串作为变量。
如果要将命令转换为字符串,请进行转换:
$str = $codeQuery->getRawSql(); // get sql statement
$res = $codeQuery->execute(); // execute sql statement