minity/yii2-model-setup

在一个地方配置所有模型方面。

v0.1.0 2017-10-22 23:02 UTC

This package is auto-updated.

Last update: 2024-09-28 14:55:00 UTC


README

如果你在添加或检查Yii2模型属性时,觉得查找数十种方法感到不舒服,可以考虑使用这些特质。

示例

通常,创建任何ActiveRecord模型我们必须定义几个方法,例如tableName()attributeLabels()attributeHints()rules()fields()

使用\Minity\ModelSetup\ActiveRecordConfigurationTrait,我们只需要定义以下setup()方法

<?php

use Minity\ModelSetup\ActiveRecordConfigurationTrait;
use yii\db\ActiveRecord;

class Record extends ActiveRecord
{
    use ActiveRecordConfigurationTrait;
    
    protected static function setup() {
        return [
            'tableName' => '{{%record}}',
            'attributes' => [
                'field1' => [
                    'label' => 'Record Field 1',
                    'hint' => 'Record Hint 1',
                    'toArray' => 'record_field_1',
                    'rules' => ['required', ['number', 'min' => 0]],
                ],
                'field2' => [
                    'label' => 'Record Field 2',
                    'hint' => 'Record Hint 2',
                    'toArray' => true, // the same as 'field2'
                    'rules' => ['string'],
                ],
                'field3' => [
                    'label' => 'Record Field 3',
                    //'toArray' => false, // default
                    'rules' => ['safe'],
                ],
            ],
            'relations' => [
                'rel1' => ['hasOne', AnotherRecord::className(), ['id' => 'field1']],
                'rel2' => ['hasMany', ViaRecord::className(), ['id' => 'via_id'],
                    'viaTable' => ['junction_table', ['rec_id' => 'id']],
                ],
            ]
        ];
    }
}

注意relations部分。你可以看到其中定义关系的声明式方法,因此你可以通过调用$model->getRel1()获取ActiveQuery对象,或者通过调用$model->rel1获取ActiveRecord。