放入cakephp之前截断表

编程入门 行业动态 更新时间:2024-10-27 20:31:55
本文介绍了放入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源> \Phinx\Seed\SeedInterface :: execute()
  • Phinx存储库>拉取请求>添加表截断方法
  • Phinx Source > \Phinx\Seed\SeedInterface::execute()
  • Phinx Repository > Pull Requests > Add table truncate method

更多推荐

放入cakephp之前截断表

本文发布于:2023-10-16 10:47:21,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1497351.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:放入   cakephp

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!