放入cakephp之前截断表 [英] Truncating table before seeding in cakephp

查看:68
本文介绍了放入cakephp之前截断表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道在使用cakephp 3播种数据库时是否有更好(更平滑)的方式来禁用外键检查,截断表,插入数据并启用外键检查。这是我当前的代码,无法正常工作

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');
    }
}

有没有办法让我不必使用ConnectionManager?例如,仅使用AbstractSeed就可以做到:

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();

您如何处理此问题?

推荐答案

使用CakePHP的连接管理器将创建一个新的独立数据库连接,即,用于播种的数据库连接将不受影响。

Using CakePHPs connection manager would create a new, separate database connection, ie the one used for seeding will not be affected.

就像迁移一样,种子基于Phinx,因此您可以简单地使用它提供的功能,例如 \Phinx\Seed SeAbstractSeed :: execute()以运行自定义SQL。

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');

另请参见

  • Phinx Source > \Phinx\Seed\SeedInterface::execute()
  • Phinx Repository > Pull Requests > Add table truncate method

这篇关于放入cakephp之前截断表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆