Yii2 - how to trim a table from the console

I created a console command and I need to trim the table.

Reading the class reference: http://www.yiiframework.com/doc-2.0/yii-db-command.html#truncateTable()-detail I can’t figure out which files I need to include to execute this command.

I'm turning on:

use yii\db\Command;
use yii\db\Connection;

but not sure which one is correct.

And I tried to execute:

$command = Yii::$app->db->truncateTable('user');

which gives me the following error:

Exception 'yii \ base \ UnknownMethodException' with the message 'Unknown method call: yii \ db \ Connection :: truncateTable ()'

and

Yii::$connection->createCommand()->truncateTable('user');

which gives me the following error:

PHP Fatal Error 'yii \ base \ ErrorException' with the message "Access to undeclared static property: Yii :: $ connection"

I really don't understand what I need to do.

+4
3
Yii::$app->db->createCommand()->truncateTable('user')->execute();
+9

yii2

yii2 migrate

1.

yii migrate/create truncate_table_xxx

Step2. xxx_truncate_table_xxx

-

class m150101_185401_truncate_table_xxx extends Migration
{
   $this->dropTable('xxx')
}
+2

Alternatively, you can use:

User::deleteAll();

Assuming that Useris the active class of the model. This command shows the number of deleted records.

Note that, unlike truncatedeleting all records, it will NOT be reset by an auto-increment counter 1.

0
source

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


All Articles