stesi / yii2-relation-trait
Yii 2 模型加载关联,并使用事务保存关联
1.1.5.2
2017-12-21 15:50 UTC
Requires
- php: >=5.4.0
- yiisoft/yii2: ~2.0
README
Yii 2 模型添加了关联加载(loadAll($POST))和事务性保存关联(saveAll())的功能
安装
安装此扩展的首选方式是通过composer。
运行以下命令:
$ composer require 'stesi/yii2-relation-trait:dev-master'
或者
"stesi/yii2-relation-trait": "*"
将以下内容添加到您的composer.json文件的require部分:
在模型中使用
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上测试了它。
我欢迎任何改进