e-frank/yii2-data

从数组持久化关系数据的助手

安装: 146

依赖项: 0

建议者: 0

安全性: 0

星标: 5

关注者: 3

分支: 3

开放问题: 0

类型:yii2-extension

1.2.0 2018-12-17 10:33 UTC

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!
  1. incremental => false (默认) 断开所有orderItems的链接,除了在$data中传递的。
  2. 除了断开链接,delete => true 还会删除这些模型。这对 incremental => true 无效
  3. 如果没有显式设置关系配置值,则使用根级别的默认值

将所有需要的关联传递给配置数组。您可以自定义相关数据的处理,如下所示,例如链接/断开链接和删除/跳过的行为。

数据示例

// 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'],
		]
	]
]

幕后

  1. ActiveDocument助手类仅将ActiveDocumentBehavior附加到ActiveRecord上。
  2. 对于每个关联,都会附加RelationValidator。这允许捕获关联的设置器(在加载时)
  3. 现在$model->load($data) 也关心关联。
  4. 在保存之前,打开事务。
  5. 如果一切有效(忽略那些跳过错误模型的模型),我们最终可以保存。
  6. 提交或回滚事务
  7. 使用$model->getErrorDocument()$model->getDocument()