Yii 2 Models add functionality for load with relation (loadAll($POST)), & transactional save with relation (saveAll())
The preferred way to install this extension is through composer.
Either run
$ composer require 'mootensai/yii2-relation-trait:dev-master'
or add
"mootensai/yii2-relation-trait": "*"
to the require
section of your composer.json
file.
class MyModel extends ActiveRecord{
use \mootensai\relation\RelationTrait;
}
It takes a normal array of POST. This is the example
// 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]);
}
#Features
// 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
)
)
)
So your data will be atomic (see : http://en.wikipedia.org/wiki/ACID)
So your behaviors still works
$form->errorSummary($model);
will give you
<<Related Class Name>> #<<index + 1>> : <<error message>>
My Related Model #1 : Attribute is required
See here if you want to use my behavior : https://github.com/mootensai/yii2-uuid-behavior
#To Do Test it on another DB. I only test it on MySQL.
I'm open for any improvement