问题
I'm wondering if there is a better (more smooth) way to disable foreign key checks, truncate table, insert data and enable foreign key checks when you seed database with cakephp 3. This is my current code which is not working
<?php
use Migrations\AbstractSeed;
use Cake\Datasource\ConnectionManager;
/**
* Categories seed.
*/
class CategoriesSeed extends AbstractSeed
{
public function run()
{
$connection = ConnectionManager::get('default');
$connection->execute('SET FOREIGN_KEY_CHECKS = 0');
$connection->execute('TRUNCATE table categories');
$data = [
['id' => 1, 'name' => 'Audio, video & photo', 'parent' => 0, 'alias' => 'audio-video-and-photo', 'image' => ''],
['id' => 2, 'name' => 'Music players', 'parent' => 1, 'alias' => 'music-players', 'image' => ''],
['id' => 3, 'name' => 'Musical instruments', 'parent' => 1, 'alias' => 'musical-instruments', 'image' => ''],
];
$table = $this->table('categories');
$table->insert($data)->save();
$connection->execute('SET FOREIGN_KEY_CHECKS = 1');
}
}
Is there a way so i don't have to use ConnectionManager? Is this possible with just a use of AbstractSeed for example:
$table = $this->table('categories');
$table->query('SET FOREIGN_KEY_CHECKS = 0');
$table->truncate();
what is your way of dealing with this problem?
回答1:
Using CakePHPs connection manager would create a new, separate database connection, ie the one used for seeding will not be affected.
Just like migrations, seeds are based on Phinx, so you can simply use the functionality provided by it, for example \Phinx\Seed\AbstractSeed::execute()
to run custom SQL.
$this->execute('SET FOREIGN_KEY_CHECKS = 0');
$this->execute('TRUNCATE TABLE categories');
$table = $this->table('categories');
$table->insert($data)->save();
$this->execute('SET FOREIGN_KEY_CHECKS = 1');
See also
- Phinx Source > \Phinx\Seed\SeedInterface::execute()
- Phinx Repository > Pull Requests > Add table truncate method
来源:https://stackoverflow.com/questions/41918577/truncating-table-before-seeding-in-cakephp