yii2-relation-trait 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": "dev-master"

to the require section of your composer.json file.

Github : mootensai/yii2-relation-trait

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->loadRelated(Yii:$app->request->post()) && $model->saveRelated()){
        return $this->redirect('view', 'id' => $model->id, 'created' => $model->created]);
    }
}

usage at model

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

Features

  1. Installation
  2. Array Output
  3. Using Transaction
  4. Use Normal Save
  5. Add Validation At Main Model
  6. It Works On Auto Incremental PK Or Not (I Have Tried Use UUID)

Array Output

// 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
                )
        )
)

Using Transaction

Your data will be atomic (see : ACID)

Use Normal Save

so your behavior still works

Add Validation At Main Model

$form->errorSummary($model);

will give you ~~~ <> #<> : <> My Related Model #1 : Attribute is required ~~~

It Works On Auto Incremental PK Or Not (I Have Tried Use UUID)

0 0
2 followers
0 downloads
Yii Version: 2.0
License: BSD-2-Clause
Category: Database
Developed by: moo.tensai
Created on: Jun 1, 2015
Last updated: 9 years ago

Related Extensions