Yii2: get raw sql of model->save()
$model->save()->rawSql
call can not return null
, it must throw an exception that you are trying to access property of non-object. $model->save()
returns boolean
value - either query executed successfully or not.
If $model->getErrors()
returns empty array and query was not executed at all I'm pretty sure that something is wrong with model event handlers, especially beforeSave()
, check it, it should not return false
. Also check attached behaviors event handlers.
As for getting query. It's useless if it simply was not executed, but if it was, here are some ways to achieve it:
1) Probably the best way. Use debug panel. I also mentioned it here.
2) Look at logs as @robsch adviced.
You can't directly get raw SQL in code with $model->save()
, It will call either insert()
or update()
. If you are interested, here is the part of code for 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;
}
If you call $command->rawSql
you will get raw sql but you can't do that outside because the command is formed internally.
P.S. This piece of code:
if ($model->validate()) {
$model->save();
}
doesn't make sense because $model->save()
will call $model->validate()
internally.