如何编写迁移以使用phinx插入记录? [英] How can I write migrations to insert records using phinx?

查看:58
本文介绍了如何编写迁移以使用phinx插入记录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 phinx 来处理新项目的迁移,现在我需要创建一个新表并插入一些行对此,我有:

I'm using phinx to handle the migration on a new project, now I need to create a new table and insert some rows to it, I have:

$tableStatus = $this->table('status');
$tableStatus->addColumn('code', 'string');
$tableStatus->addColumn('description', 'string');
$tableStatus->save();

这将添加新表,但我在文档中找不到如何插入行,但似乎可行:

This add the new table but I couldn't find at the documentation how to insert rows, but it seems possible:

AbstractMigration类所有Phinx迁移都从 AbstractMigration类.此类为以下人员提供了必要的支持 创建数据库迁移.数据库迁移可以转变 您的数据库有多种方式,例如创建新表,插入 行,添加索引并修改列.

The AbstractMigration Class All Phinx migrations extend from the AbstractMigration class. This class provides the necessary support to create your database migrations. Database migrations can transform your database in many ways such as creating new tables, inserting rows, adding indexes and modifying columns.

有可能吗?我该怎么办?

It is possible? How can I do it?

推荐答案

正如igrossiter所指出的,有一种方法可以使用,该方法的名称是 insert

As igrossiter pointed out, there is a method for this, the name of the method is insert

use Phinx\Migration\AbstractMigration;

class NewStatus extends AbstractMigration
{
    protected $statusId = 1234; //It'd be nice to use an entity constant instead of magic numbers, but that's up to you.
    protected $statusName = 'In Progress';

    /**
    * Migrate Up.
    */
    public function up()
    {
        $columns = ['id', 'name'];
        $data = [[$this->statusId, $this->statusName]];
        $table = $this->table('status');
        $table->insert($columns, $data);
        $table->saveData();   
    }

    /**
    * Migrate Down.
    */
    public function down()
    {
        $this->execute('Delete from status where id = ' . $this->statusId);
    }
}

自2015年12月2日起编辑

此方法的签名在将来的稳定版本中将更改为类似的

This method's signature will change in future stable versions to something like

$data = [
    ['id' => 1, 'name' => 'foo'],
    ['id' => 2, 'name' => 'bar']
];
$table = $this->table('status');
$table->insert($data);

更多此处的信息

这篇关于如何编写迁移以使用phinx插入记录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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