dsaru/goya

此包最新版本(dev-master)没有可用的许可证信息。

Laravel 数据库模式差异工具

dev-master 2014-11-23 19:49 UTC

This package is not auto-updated.

Last update: 2024-09-24 08:27:58 UTC


README

Goya 是一个简单的 Laravel 数据库模式管理工具。Goya 输出模式定义文件和数据库模式之间的差异,并将其应用到数据库中。

为了制作模式差异,Goya 使用 Doctrine DBAL。模式定义文件在 DBAL 模式表示中描述。

使用 Goya

创建模式定义文件(食谱)。
有关如何描述模式的信息,请参阅 DBAL 文档。

$ cat app/database/recipes/UserTable.php
<?php

use Dsaru\Goya\Recipe;
use Doctrine\DBAL\Schema\Schema;

class UserTable extends Recipe
{

	public function schema() {
		$table = $this->schema->createTable('user');

		$table->addColumn( 'id',             'integer',  ['autoincrement' => true, 'unsigned' => true] );
		$table->addColumn( 'name',           'string',   ['length' => 32] );
		$table->addColumn( 'created_at',     'datetime', [] );
		$table->addColumn( 'updated_at',     'datetime', [] );
		$table->addColumn( 'deleted_at',     'datetime', ['notnull' => false, 'default' => null] );

		$table->setPrimaryKey(['id']);
	}

}

实际数据库中尚未定义任何内容。

$ mysql -uroot yourdb 
mysql> show tables;
Empty set (0.00 sec)

如果你运行 goya 命令,将从一个模式定义文件生成 SQL。

$ php artisan goya
CREATE TABLE user (id INT UNSIGNED AUTO_INCREMENT NOT NULL, name VARCHAR(32) NOT NULL, created_at DATETIME NOT NULL, updated_at DATETIME NOT NULL, deleted_at DATETIME DEFAULT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB

你可以使用 goya:cook 命令将其应用到实际数据库中。

$ php artisan goya:cook

$ mysql -uroot yourdb 
mysql> desc user;
+------------+------------------+------+-----+---------+----------------+
| Field      | Type             | Null | Key | Default | Extra          |
+------------+------------------+------+-----+---------+----------------+
| id         | int(10) unsigned | NO   | PRI | NULL    | auto_increment |
| name       | varchar(32)      | NO   |     | NULL    |                |
| created_at | datetime         | NO   |     | NULL    |                |
| updated_at | datetime         | NO   |     | NULL    |                |
| deleted_at | datetime         | YES  |     | NULL    |                |
+------------+------------------+------+-----+---------+----------------+
5 rows in set (0.00 sec)

现在,将 profile 列定义添加到模式定义文件中。

$table->addColumn( 'profile',        'string',   ['length' => 1000] );

再次运行 goya 命令。

$ php artisan goya
ALTER TABLE user ADD profile VARCHAR(1000) NOT NULL

安装

将此包名称添加到 composer.json

"require": {
    ...,
    "dsaru/goya": "dev-master"
}

运行 composer update

打开 app/config/app.php,并添加 Service Provider。

'providers' => array(
 	..
	'Dsaru\Goya\GoyaServiceProvider', 
),

编写食谱

模式定义文件(食谱)位于 app/database/recipes
你可以在单个文件中描述多个表定义。或者,它们也可以分为多个文件。

食谱文件需要命名为 [ClassName].php。在文件中创建一个扩展 \Dsaru\Goya\Recipe 的类,并在 schema 方法中描述数据库表模式。

class MyTables extends \Dsaru\Goya\Recipe
{
	public function schema() {
		// write database definitions here
	}
}

当你使用多个食谱文件时,你可能需要控制文件加载的顺序。
因为食谱是按字母顺序加载的,如果它们命名为 001_[ClassName]].php002_[ClassName].php,那么它们将正常工作。

作者

daisaru11 <daisaru11@gmail.com>