遇到Cakephp数据库迁移问题

时间:2016-10-14 11:57:20

标签: php mysql cakephp

我正在尝试使用数据库迁移创建一个表,这是我的代码

    public function change()
    {
        $table = $this->table('tags');
        $table->addColumn('title', 'string', ['default' => null,'limit' => 255,'null' => false,]);
        $table->addColumn('created', 'datetime', ['default' => null,'null' => false,]);
        $table->addColumn('modified', 'datetime', ['default' => null,'null' => false,]);
        $table->addUniqueKey('title');         // Giving error **Fatal error: Call to undefined method Phinx\Db\Table::addUniqueKey()**
        $table->create();
    }

我想将title列设置为唯一,但是当我尝试执行此操作时,它会给出错误:

  

致命错误:调用未定义的方法Phinx \ Db \ Table :: addUniqueKey()

2 个答案:

答案 0 :(得分:0)

添加主键,请参阅http://book.cakephp.org/3.0/en/orm/schema-system.html

    public function change() {
        $t = new Table('posts');
        $t->addColumn('id', 'integer')
          ->addColumn('author_id', 'integer')
          ->addColumn('title', 'string')
          ->addColumn('slug', 'string');

        // Add a primary key.
        $t->addConstraint('primary', [
            'type' => 'primary',
            'columns' => ['id']
        ]);

        // Add a unique key
        $t->addConstraint('slug_idx', [
            'columns' => ['slug'],
            'type' => 'unique',
        ]);

        // Add index
        $t->addIndex('slug_title', [
            'columns' => ['slug', 'title'],
            'type' => 'index'
        ]);

        // Add a foreign key
        $t->addConstraint('author_id_idx', [
            'columns' => ['author_id'],
            'type' => 'foreign',
            'references' => ['authors', 'id'],
            'update' => 'cascade',
            'delete' => 'cascade'
        ]);
    }

答案 1 :(得分:0)

这应该是解决方案

$table->addColumn('title', 'string', 
[
    'default' => null,
    'limit' => 255,
    'null' => false,
]);
$table->addIndex(['title'], ['unique' => true]); // < this is what you looking for

我很惊讶CakePHP文档没有正确提及它。经过长时间的搜索,我在此article

中找到了解决方案