Yii2: get raw sql models-> save ()

I want to add a record to a table using ActiveRecord .

Here is my code:

 $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() returns true , but $model->save() returns false .

How to find the generated raw sql $model->save() ?

Meanwhile:

$model->save()->rawSql - null , and $model->getErrors() returns an empty array.

In debug mode, all requests are logged, but I did not find any insert or update requests.

+6
source share
1 answer

$model->save()->rawSql call cannot return null , it should throw an exception to which you are trying to access a non-object property. $model->save() returns boolean - either the request completed successfully or not.

If $model->getErrors() returns an empty array and the request has not been executed at all, I'm sure that something is wrong with the model's event handlers, especially beforeSave() , check this, it should not return false . Also check event handlers for event handlers.

How to get a request. It is useless if it simply has not been executed, but if it was, here are a few ways to achieve it:

1) Probably the best way. Use the debug panel. I also mentioned this here .

2) Look at the magazines as @robsch advised.

You cannot directly get raw SQL code with the code $model->save() , it will call either insert() or update() . If you're interested, here is the code part 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 get a raw sql, but you can not make it outside, because the team is formed inside.

PS This piece of code:

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

doesn't make sense because $model->save() will internally call $model->validate() .

+3
source

Source: https://habr.com/ru/post/986911/


All Articles