e-frank / yii2-data
从数组持久化关系数据的助手
1.2.0
2018-12-17 10:33 UTC
Requires
- php: >=5.4.0
- yiisoft/yii2: ~2.0.6
This package is auto-updated.
Last update: 2024-09-18 02:47:25 UTC
README
支持关系和排序的ActiveRecord分层填充器。
使用方法
$document = new \x1\data\ActiveDocument([ 'model' => Order::className(), // 'useTransaction' => true, // 'defaultIncremental' => false, // 'defaultIgnoreError' => false, // 'defaultDelete' => true, // 'defaultScenario' => null, // 'defaultSkipUpdate' => false, // 'defaultIgnoreError' => false, 'relations' => [ 'orderItems' => [ // 'incremental' => false, // sets relations as passed by data and unlinks omitted rows // 'skipUpdate' => false, // models are save, otherwise they are skipped // 'delete' => true, // deletes dropped models, otherwise they are only unlinked // 'scenario' => null, // the scenario to use for validation // 'useTransaction' => true, // wraps all operations in a transaction // 'sortable' => null, // (string) name of the order column (=int field) 'relations' => ['supplier'], // other relations of 'orderItem', maybe nested ] ], ]); $model = $document->findOne(1); // find the model and quietly attach ActiveDocumentBehavior $model->load($data); // relations are set!
incremental => false
(默认) 断开所有orderItems的链接,除了在$data
中传递的。- 除了断开链接,
delete => true
还会删除这些模型。这对incremental => true
无效 - 如果没有显式设置关系配置值,则使用根级别的默认值
将所有需要的关联传递给配置数组。您可以自定义相关数据的处理,如下所示,例如链接/断开链接和删除/跳过的行为。
数据示例
// data from post $data = [ 'Order' => [ 'id' => 1, 'title' => 'Order #1' 'orderItems' => [ ['id' => 1, 'msg' => 'order item #1'], ['id' => 2, 'msg' => 'order item #2'], [ 'msg' => 'unsaved order item #3'], ] ] ]
幕后
- ActiveDocument助手类仅将ActiveDocumentBehavior附加到ActiveRecord上。
- 对于每个关联,都会附加RelationValidator。这允许捕获关联的设置器(在加载时)
- 现在
$model->load($data)
也关心关联。 - 在保存之前,打开事务。
- 如果一切有效(忽略那些跳过错误模型的模型),我们最终可以保存。
- 提交或回滚事务
- 使用
$model->getErrorDocument()
和$model->getDocument()