marena / yii2-relation-trait

Yii 2 模型加载关系,并使用关系进行事务保存

安装次数 1,646

依赖项: 2

建议者: 0

安全性: 0

星标: 0

关注者: 1

分支: 45

类型:yii2-extension

1.1.8 2023-03-08 08:58 UTC

This package is auto-updated.

Last update: 2024-09-08 12:14:22 UTC


README

Yii 2 模型添加了加载关系的功能(loadAll($POST)),以及使用关系进行事务保存(saveAll())

Latest Stable Version License Total Downloads Join the chat at https://gitter.im/mootensai/yii2-relation-trait

安装

通过以下方式安装此扩展是首选:

运行

$ composer require 'mootensai/yii2-relation-trait:dev-master'

或者将以下内容添加到您的 composer.json 文件的 require 部分:

"mootensai/yii2-relation-trait": "*"

to the require section of your composer.json file.

在模型中的使用

class MyModel extends ActiveRecord{
    use \mootensai\relation\RelationTrait;
}

数组输入及控制器中的使用

它需要一个普通的 POST 数组。以下是一个例子

// sample at controller
//$_POST['ParentClass'] = ['attr1' => 'value1','attr2' => 'value2'];
//$_POST['RelatedClass'][0] = ['attr1' => 'value1','attr2' => 'value2'];      
if($model->loadAll(Yii:$app->request->post()) && $model->saveAll()){
    return $this->redirect(['view', 'id' => $model->id, 'created' => $model->created]);
}

##功能

数组输出

// I use this to send model & related through JSON / Serialize
print_r($model->getAttributesWithRelatedAsPost());
Array
(
    [MainClass] => Array
        (
            [attr1] => value1
            [attr2] => value2
        )

    [RelatedClass] => Array
        (
            [0] => Array
                (
                    [attr1] => value1
                    [attr2] => value2
                )
        )

)
print_r($model->getAttributesWithRelated());
Array
(
    [attr1] => value1
    [attr2] => value2
    [relationName] => Array
        (
            [0] => Array
                (
                    [attr1] => value1
                    [attr2] => value2
                )
        )
)

使用事务

这样您的数据将是原子性的(见: http://en.wikipedia.org/wiki/ACID

使用普通保存

这样您的行为仍然有效

在主模型中添加验证

$form->errorSummary($model);

将会得到

<<Related Class Name>> #<<index + 1>> : <<error message>>
My Related Model #1 : Attribute is required

它适用于自增主键或非自增主键(我已尝试使用 UUID)

如果您想使用我的行为,请参阅:https://github.com/mootensai/yii2-uuid-behavior

##要在另一个数据库上测试它。我只在 MySQL 上进行了测试。

我欢迎任何改进