inquid / yii2-relation-traits
Yii 2 模型使用关系加载,MongoDB 中使用关系事务保存
1.1.9
2019-12-24 07:44 UTC
Requires
- php: >=5.4.0
- yiisoft/yii2: ~2.0
README
Yii 2 模型添加了加载关系(loadAll($POST))和事务保存关系(saveAll())的功能
PLUS 软删除/恢复功能!适用于 MongoDB!
支持 Mootnesai
https://www.paypal.me/yohanesc
在 LinkedIn 上支持我
https://www.linkedin.com/in/yohanes-candrajaya-b68394102/
安装
安装此扩展的首选方式是通过 composer。
运行
$ composer require 'mootensai/yii2-relation-trait:dev-master'
或添加
"mootensai/yii2-relation-trait": "*"
到您的 composer.json
文件的 require
部分。
在模型中使用
class MyModel extends ActiveRecord{ use \mootensai\relation\RelationTrait; }
数组输入和控制器中的使用
它接受一个正常的 POST 数组。以下是一个示例
Array ( $_POST['ParentClass'] => Array ( [attr1] => value1 [attr2] => value2 // has many [relationName] => Array ( [0] => Array ( [relAttr] => relValue1 ) [1] => Array ( [relAttr] => relValue1 ) ) // has one [relationName] => Array ( [relAttr1] => relValue1 [relAttr2] => relValue2 ) ) ) OR Array ( $_POST['ParentClass'] => ['attr1' => 'value1','attr2' => 'value2'], // Has One $_POST['RelatedClass'] => ['relAttr1' => 'value1','relAttr2' => 'value2'], // Has Many $_POST['RelatedClass'] => Array ( [0] => Array ( [attr1] => value1 [attr2] => value2 ) [1] => Array ( [attr1] => value1 [attr2] => value2 ) ) )
// sample at controller 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
它适用于自增 PK 或非自增 PK(我已尝试使用 UUID)
如果您想使用我的行为,请参阅此处
https://github.com/mootensai/yii2-uuid-behavior
软删除
将此行添加到您的模型中,以启用软删除
private $_rt_softdelete; function __construct(){ $this->_rt_softdelete = [ '<column>' => <undeleted row marker value> // multiple row marker column example 'isdeleted' => 1, 'deleted_by' => \Yii::$app->user->id, 'deleted_at' => date('Y-m-d H:i:s') ]; }
将此行添加到您的模型中,以启用软恢复
private $_rt_softrestore; function __construct(){ $this->_rt_softrestore = [ '<column>' => <undeleted row marker value> // multiple row marker column example 'isdeleted' => 0, 'deleted_by' => 0, 'deleted_at' => 'NULL' ]; }
应在 Yii 支持的数据库上工作
它使用 Yii 的所有 Active Query 或 Active Record 执行数据库命令
我欢迎任何改进
如果您遇到问题或对增强有想法,请创建问题