Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php Yii2:获取模型的原始sql->;保存()_Php_Activerecord_Yii_Yii2 - Fatal编程技术网

Php Yii2:获取模型的原始sql->;保存()

Php Yii2:获取模型的原始sql->;保存(),php,activerecord,yii,yii2,Php,Activerecord,Yii,Yii2,我想将记录添加到带有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->valid

我想将记录添加到带有
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()
$model->save()
返回
boolean
值-查询是否成功执行

如果
$model->getErrors()
返回空数组,并且查询根本没有执行,我很确定模型事件处理程序有问题,特别是
beforeSave()
,请检查它,它不应该
返回false
。还要检查附加的行为事件处理程序

至于获取查询。如果只是不执行它是没有用的,但如果执行了,以下是实现它的一些方法:

1)可能是最好的方法。使用调试面板。我也提到过

2)查看@robsch建议的日志

使用
$model->save()
无法直接在代码中获取原始SQL,它将调用
insert()
update()
。如果您感兴趣,以下是
insertInternal()
的代码部分:

如果调用
$command->rawSql
,您将获得原始sql,但您不能在外部执行,因为该命令是在内部形成的

p.S.这段代码:

if ($model->validate()) {
    $model->save();
}

没有意义,因为
$model->save()
将在内部调用
$model->validate()

此代码不会准确显示原始sql,但会得到查询预绑定和参数

试试看{
//这将模拟$model->save();
$builder=$model->getCommandBuilder();
$table=$model->getTableSchema();
$command=$builder->createInsertCommand($table,$model->getAttributes());
$command->_connection->enableParamLogging=true;
$command->execute();
}捕获(例外$e){
//getText()将使用绑定参数打印查询
//getAttributes()将为您提供注入的属性
var_dump($command->getText());
变量转储($model->getAttributes());
模具();
}
结果如下所示:

"INSERT INTO `fruit` (`order`, `name`, `season`) VALUES (:yp0, :yp1,:yp2)"

array(2) {
  ["order"] =>  int(1),
  ["name"] =>  null,
  ["season"] =>  null
}

如果处于调试模式,则可以查看runtime/logs/app.log。查询也会被记录。问题来自于
beforeSave
"INSERT INTO `fruit` (`order`, `name`, `season`) VALUES (:yp0, :yp1,:yp2)"

array(2) {
  ["order"] =>  int(1),
  ["name"] =>  null,
  ["season"] =>  null
}