Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

yii2 - how to truncate a table from console

Tags:

php

yii2

I have created a console command and I need to truncate a table.

Reading the Class reference: http://www.yiiframework.com/doc-2.0/yii-db-command.html#truncateTable()-detail I am not able to understand what files I need to include in order to execute this command.

I am including:

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

but not sure which one is correct.

And I have tried to execute:

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

which gives me the following error:

Exception 'yii\base\UnknownMethodException' with message 'Calling unknown method: yii\db\Connection::truncateTable()'

and:

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

which gives me the following error:

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

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

like image 817
MeV Avatar asked Feb 17 '16 15:02

MeV


2 Answers

Yii::$app->db->createCommand()->truncateTable('user')->execute();
like image 130
Onedev_Link Avatar answered Oct 06 '22 13:10

Onedev_Link


Using yii2 migrate that default function

yii2 migrate

Step 1. Create a migrate

yii migrate/create truncate_table_xxx

Step2. Edit file xxx_truncate_table_xxx

Some thing like that

class m150101_185401_truncate_table_xxx extends Migration
{
   $this->dropTable('xxx')
}
like image 30
t10508hn Avatar answered Oct 06 '22 15:10

t10508hn