Load & Save With Relation

You are viewing revision #11 of this wiki article.
This version may not be up to date with the latest version.
You may want to view the differences to the latest version.

next (#12) »

yii2-relation-trait

  1. Installation
  2. Usage

Yii 2 Models add functionality for load with relation, & transactional save with relation

Installation

The preferred way to install this extension is through composer.

Either run ~~~ $ composer require mootensai/yii2-relation-trait ~~~

or add

"mootensai/yii2-relation-trait": "*"

to the require section of your composer.json file.

Usage

It takes a normal array of POST. This is the example

$POST['ParentClass'] = ['attr1' => 'value1','attr2' => 'value2'];
$POST['RelatedClass'][0] = ['attr1' => 'value1','attr2' => 'value2'];        

usage at controller

public function actionCreate(){
    $model = new MyModel;
    if($model->loadAll(Yii:$app->request->post()) && $model->saveAll()){
        return $this->redirect('view', 'id' => $model->id, 'created' => $model->created]);
    }
}

usage at model

class MyModel extends ActiveRecord{
    use \mootensai\relation\RelationTrait;
}

output

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
                )
        )
)
1 0
2 followers
Viewed: 18 434 times
Version: Unknown (update)
Category: Tips
Written by: moo.tensai
Last updated by: moo.tensai
Created on: May 27, 2015
Last updated: 9 years ago
Update Article

Revisions

View all history