tecnocen / yii2-migrate
处理规范化表创建的Yii 2库
1.0.2
2017-08-07 20:37 UTC
Requires
- php: >=5.5
- yiisoft/yii2: ~2.0.10
Requires (Dev)
- codeception/base: ^2.2.3
- codeception/verify: ~0.3.1
This package is not auto-updated.
Last update: 2024-09-15 02:24:41 UTC
README
此库通过提供单独创建表的类来简化规范化数据库的创建。
安装
您可以使用composer安装库tecnocen/migrate
,运行以下命令:
composer require tecnocen/migrate
或编辑composer.json
文件
require: { "tecnocen/yii2-migrate": "*", }
使用方法
创建表迁移
您可以使用tecnocen\migrate\CreateTableMigration
来生成不同类型的迁移表,用于您的每种表类型。
例如,假设您想保存谁和何时修改或创建了系统中的每个实体,但您的交叉表只需要知道它们何时被创建,因为它们不能被编辑。
abstract class EntityTable extends \tecnocen\migrate\CreateTableMigration { public function defaultColumns() { return [ 'created_at' => $this->datetime()->notNull(), 'updated_at' => $this->datetime()->notNull(), 'created_by' => $this->normalKey(), 'updated_by' => $this->normalKey(), ] } public function defaultForeignKeys() { return [ 'created_by' => 'user', 'updated_by' => 'user', ]; } } abstract class PivotTable extends \tecnocen\migrate\CreateTableMigration { public function defaultColumns() { return [ 'created_at' => $this->datetime()->notNull(), ] } }
然后您可以为每种类型的表单独使用它们
class m170101_010101_ticket extends EntityTable { public function columns() { return [ 'id' => $this->primaryKey(), 'project_id' => $this->normalKey(), 'title' => $this->string(150)->notNull(), 'description' => $this->text(), ]; } public function foreignKeys() { return ['project_id' => ['table' => 'project']]; } } class m17010101_010102_ticket_employee extends PivotTable { public function columns() { return [ 'ticket_id' => $this->normalKey(), 'employee_id' => $this->normalKey(), ]; } public function foreignKeys() { return [ 'ticket_id' => ['table' => 'ticket'], 'employee_id' => ['table' => 'employee'], ]; } public function compositePrimaryKeys() { return ['ticket_id', 'employee_id']; } }
当运行迁移m170101_010101_ticket
时,它将生成一个包含以下列的表
id
,project_id
,title
,description
,created_by
,updated_by
created_at
,updated_at
主键为id
,并连接到列project_id
、created_by
和updated_by
的三个外键。
而迁移m170101_010101_ticket_employee
将生成一个包含以下列的表。
ticket_id
employee_id
created_at
具有由列ticket_id
和employee_id
组成的复合主键,并连接到前面两个列的两个外键。
创建视图迁移
您可以使用tecnocen\migrate\CreateViewMigration
来生成SQL视图迁移。
use tecnocen\migrate\CreateViewMigration; use common\models\Ticket; class m17010101_010101_ticket_details extends CreateViewMigration { /** * @inheritdoc */ public function viewName() { return 'ticket_details'; } /** * @inheritdoc */ public function viewQuery() { return Ticket::find() ->alias('t') ->innerJoinWith([ 'project' => function ($query) { $query->alias('p'); }, ])->select([ 'ticket_id' => 't.id', 'project_id' => 'p.id', 'ticket_title' => 't.title', 'ticket_description' => 't.description', 'project_name' => 'p.name',t ]); } }
其中viewName()
返回一个字符串,而viewQuery()
返回一个yii\db\Query
实例。