Yii 2:获取模型的原始sql->保存()

vom3gejh  于 2022-11-09  发布在  其他
关注(0)|答案(2)|浏览(160)

我想用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()->rawSqlnull,并且$model->getErrors()返回空数组。
在调试中,所有查询都被记录,但我没有找到任何插入或更新查询。

jjhzyzn0

jjhzyzn01#

$model->save()->rawSql调用无法返回null,它必须引发异常,表明您正在尝试访问非对象的属性。$model->save()返回boolean值-查询执行成功与否。
如果$model->getErrors()返回空数组,并且根本没有执行查询,我很确定模型事件处理程序有问题,尤其是beforeSave(),请检查它,它不应该是return false还要检查事件处理程序附加行为
至于获取查询,如果只是没有执行它是没有用的,但是如果执行了,这里有一些方法可以实现它:

**1)**可能是最好的方法。使用调试面板。我在这里也提到过。
**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,但是你不能在外部这样做,因为命令是在内部形成的。
这段代码

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

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

7cjasjjr

7cjasjjr2#

这段代码不会准确地显示原始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
}

相关问题