我想用ActiveRecord
将记录添加到表中。
这是我的代码:
$model = new Article();
$model->title = 'test title';
$model->content = 'test content';
$model->category_id = 1;
$model->author_id = 1;
if ($model->validate()) {
$model->save();
}
[$model->validate()
返回true
,但是$model->save()
返回false
。
如何查找$model->save()
的生成的原始sql?
同时:
[$model->save()->rawSql
是null
,并且$model->getErrors()
返回空数组。
在调试中,将记录所有查询,但是我没有找到任何插入或更新查询。
$model->save()->rawSql
调用不能返回null
,它必须抛出一个异常,您正在尝试访问非对象的属性。 $model->save()
返回boolean
值-查询是否成功执行。
如果$model->getErrors()
返回空数组并且根本不执行查询,我很确定模型事件处理程序(尤其是beforeSave()
)出了点问题,请检查它,而不是return false
。还要检查附加的行为事件处理程序。
关于查询。如果只是不执行,它是没有用的,但是如果是的话,以下是实现它的一些方法:
1)可能是最好的方法。使用调试面板。我也提到了它here。
[2)按照@robsch建议的方式查看日志。
您无法使用$model->save()
直接获取原始SQL代码,它将调用insert()
或update()
。如果您有兴趣,请参阅insertInternal()
的代码部分:
$values = $this->getDirtyAttributes($attributes);
if (empty($values)) {
foreach ($this->getPrimaryKey(true) as $key => $value) {
$values[$key] = $value;
}
}
$db = static::getDb();
$command = $db->createCommand()->insert($this->tableName(), $values);
if (!$command->execute()) {
return false;
}
如果调用$command->rawSql
,将获得原始sql,但由于命令是在内部形成的,因此您无法在外部执行此操作。
P.S。此段代码:
if ($model->validate()) {
$model->save();
}
没有意义,因为$model->save()
将在内部调用$model->validate()
。
此代码不会向您确切显示原始sql,但您将获得查询预绑定和参数
try {
// this will simulate $model->save();
$builder = $model->getCommandBuilder();
$table = $model->getTableSchema();
$command = $builder->createInsertCommand($table, $model->getAttributes());
$command->_connection->enableParamLogging = true;
$command->execute();
} catch (Exception $e) {
// getText() will print the query with the binding params
// getAttributes() will give you the attributes injected
var_dump($command->getText());
var_dump($model->getAttributes());
die();
}
结果将看起来像:
"INSERT INTO `fruit` (`order`, `name`, `season`) VALUES (:yp0, :yp1,:yp2)"
array(2) {
["order"] => int(1),
["name"] => null,
["season"] => null
}