consultnn/yii2-mongodb-embedded

Yii2行为实现了处理mongodb嵌入式文档的功能

v1.0.5 2023-03-12 19:21 UTC

This package is auto-updated.

Last update: 2024-09-12 23:15:53 UTC


README

  • 将名称以下划线开头的新属性添加到模型中。
/**
* @inheritdoc
*/
public function attributes()
{
    return [
        '_address',
        '_phones',
    ]
}
  • 为名称不带下划线的属性添加"safe"验证规则。
/**
 * @inheritdoc
 */
public function rules()
{
    return [
            [['address', 'phones'], 'safe'],
        ]
}
  • 添加具有名称中包含下划线的属性的属性
'address' => [
    'class' => EmbedsOneBehavior::className(),
    'attribute' => '_address',
    'embedded' => Address::className()
],
'phones' => [
    'class' => EmbedsManyBehavior::className(),
    'attribute' => '_phones',
    'embedded' => Phone::className()
],
class Phone extends EmbeddedDocument 
{
    public $number;
    public $type;
    
    public function rules()
    {
        return [
            [['number', 'type'], 'string'],
            [['type'], 'in', 'range' => ['home', 'work']],
        ];
    }
}
  • 要创建空嵌入式文档,请将基文档的场景设置为EmbedsManyBehavior的initEmptyScenarios参数中列出的值
'address' => [
    'class' => EmbedsOneBehavior::className(),
    'attribute' => '_address',
    'initEmptyScenarios' => ['create', 'update'],
    'embedded' => Address::className()
],
  • 在表单或视图中使用不带下划线的属性
// Address
echo $form->field($company->address, 'detail');
echo $form->field($company->address, 'id')->hiddenInput();

// Phones
foreach($company->phones as $key => $phone) {
    echo $form->field($phone, 'number');
    echo $form->field($phone, 'type');
}