2017 © Pedro Peláez
 

yii2-extension yii2-save-relations-behavior

Validate and save automatically related Active Record models.

image

la-haute-societe/yii2-save-relations-behavior

Validate and save automatically related Active Record models.

  • Saturday, April 7, 2018
  • by juban
  • Repository
  • 11 Watchers
  • 64 Stars
  • 20,500 Installations
  • PHP
  • 13 Dependents
  • 0 Suggesters
  • 13 Forks
  • 2 Open issues
  • 16 Versions
  • 25 % Grown

The README.md

Yii2 Active Record Save Relations Behavior

Automatically validate and save related Active Record models., (*1)

Latest Stable Version Total Downloads Code Coverage Build Status Latest Unstable Version License, (*2)

Features

  • Both hasMany() and hasOne() relations are supported
  • Works with existing as well as new related models
  • Compound primary keys are supported
  • Only pure Active Record API is used so it should work with any DB driver
  • As of 1.5.0 release, related records can now be deleted along with the main model
  • ⚠️ As of 2.0.0 release, relations attributes now honor the safe validation rule

Installation

The preferred way to install this extension is through composer., (*3)

Either run, (*4)

php composer.phar require --prefer-dist la-haute-societe/yii2-save-relations-behavior "*"

or add, (*5)

"la-haute-societe/yii2-save-relations-behavior": "*"

to the require section of your composer.json file., (*6)

Configuring

Configure model as follows, (*7)

use lhs\Yii2SaveRelationsBehavior\SaveRelationsBehavior;

class Project extends \yii\db\ActiveRecord
{
    use SaveRelationsTrait; // Optional

    public function behaviors()
    {
        return [
            'timestamp'     => TimestampBehavior::className(),
            'blameable'     => BlameableBehavior::className(),
            ...
            'saveRelations' => [
                'class'     => SaveRelationsBehavior::className(),
                'relations' => [
                    'company',
                    'users',
                    'projectLinks' => ['cascadeDelete' => true],
                    'tags'  => [
                        'extraColumns' => function ($model) {
                            /** @var $model Tag */
                            return [
                                'order' => $model->order
                            ];
                        }
                    ]
                ],
            ],
        ];
    }

    public function rules()
    {
        return [
            [['name', 'company_id'], 'required'],
            [['name'], 'unique', 'targetAttribute' => ['company_id', 'name']],
            [['company', 'users', 'projectLinks', 'tags'], 'safe']
        ];
    }

    public function transactions()
    {
        return [
            self::SCENARIO_DEFAULT => self::OP_ALL,
        ];
    }

    ...


    /**
     * @return ActiveQuery
     */
    public function getCompany()
    {
        return $this->hasOne(Company::className(), ['id' => 'company_id']);
    }

    /**
     * @return ActiveQuery
     */
    public function getProjectUsers()
    {
        return $this->hasMany(ProjectUser::className(), ['project_id' => 'id']);
    }

    /**
     * @return ActiveQuery
     */
    public function getUsers()
    {
        return $this->hasMany(User::className(), ['id' => 'user_id'])->via('ProjectUsers');
    }

    /**
     * @return ActiveQuery
     */
    public function getProjectLinks()
    {
        return $this->hasMany(ProjectLink::className(), ['project_id' => 'id']);
    }

    /**
     * @return ActiveQuery
     */
    public function getTags()
    {
        return $this->hasMany(Tag::className(), ['id' => 'tag_id'])->viaTable('ProjectTags', ['project_id' => 'id']);
    }
}

Though not mandatory, it is highly recommended to activate the transactions for the owner model. ⚠️ Relations attributes has to be defined as safe in owner model validation rules in order to be saved., (*8)

Usage

Every declared relations in the relations behavior parameter can now be set and saved as follow:, (*9)

$project = new Project();
$project->name = "New project";
$project->company = Company::findOne(2);
$project->users = User::findAll([1,3]);
$project->save();

You can set related model by only specifying its primary key:, (*10)

$project = new Project();
$project->name = "Another project";
$project->company = 2;
$project->users = [1,3];
$project->save();

You can even set related models as associative arrays like this:, (*11)

$project = Project::findOne(1);
$project->company = ['name' => 'GiHub', 'description' => 'Awesome']; // Will create a new company record
// $project->company = ['id' => 3, 'name' => 'GiHub', 'description' => 'Awesome']; // Will update an existing company record
$project->save();

Attributes of the related model will be massively assigned using the `load() method. So remember to declare the according attributes as safe in the rules of the related model., (*12)

Note: Only newly created or changed related models will be saved. See the PHPUnit tests for more examples., (*13)

Populate additional junction table columns in a many-to-many relation

In a many-to-many relation involving a junction table additional column values can be saved to the junction table for each model. See the configuration section for examples., (*14)

Note: If junction table properties are configured for a relation, the rows associated with the related models in the junction table will be deleted and inserted again on each saving to ensure that changes to the junction table properties are saved too., (*15)

Validation

Every declared related models will be validated prior to be saved. If any validation fails, for each related model attribute in error, an error associated with the named relation will be added to the owner model., (*16)

For hasMany() relations, the index of the related model will be used to identify the associated error message., (*17)

It is possible to specify the validation scenario for each relation by declaring an associative array in which the scenario key must contain the needed scenario value. For instance, in the following configuration, the links related records will be validated using the Link::SOME_SCENARIO scenario:, (*18)

...
    public function behaviors()
    {
        return [
            'saveRelations' => [
                'class'     => SaveRelationsBehavior::className(),
                'relations' => ['company', 'users', 'links' => ['scenario' => Link::SOME_SCENARIO]]
            ],
        ];
    }
...

It is also possible to set a relation scenario at runtime using the setRelationScenario as follow:, (*19)

$model->setRelationScenario('relationName', 'scenarioName');

Tips: For relations not involving a junction table by using the via() or viaTable() methods, you should remove the attributes pointing to the owner model from the 'required' validation rules to be able to pass the validations., (*20)

Note: If an error occurs for any reason during the saving process of related records in the afterSave event, a yii\db\Exception will be thrown on the first occurring error. An error message will be attached to the relation attribute of the owner model. In order to be able to handle these cases in a user-friendly way, one will have to catch yii\db\Exception exceptions., (*21)

For DBMs with no built in relational constraints, as of 1.5.0 release, one can now specify a relation to be deleted along with the main model., (*22)

To do so, the relation should be declared with a property cascadeDelete set to true. For example, related projectLinks records will automatically be deleted when the main model will be deleted:, (*23)

...
'saveRelations' => [
    'class'     => SaveRelationsBehavior::className(),
    'relations' => [
        'projectLinks' => ['cascadeDelete' => true]
    ],
],
...

Note:. Every records related to the main model as they are defined in their ActiveQuery statement will be deleted., (*24)

Populate the model and its relations with input data

This behavior adds a convenient method to load relations models attributes in the same way that the load() method does. Simply call the loadRelations() with the according input data., (*25)

For instance:, (*26)

$project = Project::findOne(1);
/**
 * $_POST could be something like:
 * [
 *     'Company'     => [
 *         'name' => 'YiiSoft'
 *     ],
 *     'ProjectLink' => [
 *         [
 *             'language' => 'en',
 *             'name'     => 'yii',
 *             'link'     => 'http://www.yiiframework.com'
 *         ],
 *         [
 *             'language' => 'fr',
 *             'name'     => 'yii',
 *             'link'     => 'http://www.yiiframework.fr'
 *         ]
 *     ]
 * ];
 */
$project->loadRelations(Yii::$app->request->post());

You can even further simplify the process by adding the SaveRelationsTrait to your model. In that case, a call to the load() method will also automatically trigger a call to the loadRelations() method by using the same data, so you basically won't have to change your controllers., (*27)

The relationKeyName property can be used to decide how the relations data will be retrieved from the data parameter., (*28)

Possible constants values are:, (*29)

  • SaveRelationsBehavior::RELATION_KEY_FORM_NAME (default): the key name will be computed using the model formName() method
  • SaveRelationsBehavior::RELATION_KEY_RELATION_NAME: the relation name as defined in the behavior declarations will be used

Get old relations values

To retrieve relations value prior to there most recent modification until the model is saved, the following methods can be used:, (*30)

  • getOldRelation($name): Get a named relation old value.
  • getOldRelations(): Get an array of relations index by there name with there old values.

Notes:, (*31)

  • If a relation has not been modified yet, its initial value will be returned
  • Only relations defined in the behavior parameters will be returned

Get dirty relations

To deal with dirty (modified) relations since the model was loaded, the following methods can be used:, (*32)

  • getDirtyRelations(): Get the relations that have been modified since they are loaded (name-value pairs)
  • markRelationDirty($name): Mark a relation as dirty even if it's not been modified.

The Versions

07/04 2018

dev-delete-related-records-feature

dev-delete-related-records-feature

Validate and save automatically related Active Record models.

  Sources   Download

MIT

The Requires

 

The Development Requires

by Alban Jubert

database extension yii2 behavior active-record relations active-query has-many has-one

19/03 2018

dev-master

9999999-dev

Validate and save automatically related Active Record models.

  Sources   Download

MIT

The Requires

 

The Development Requires

by Alban Jubert

database extension yii2 behavior active-record relations active-query has-many has-one

04/03 2018

1.4.1

1.4.1.0

Validate and save automatically related Active Record models.

  Sources   Download

MIT

The Requires

 

by Alban Jubert

database extension yii2 behavior active-record relations active-query has-many has-one

22/02 2018

1.4.0

1.4.0.0

Validate and save automatically related Active Record models.

  Sources   Download

MIT

The Requires

 

by Alban Jubert

database extension yii2 behavior active-record relations active-query has-many has-one

03/11 2017

1.3.2

1.3.2.0

Validate and save automatically related Active Record models.

  Sources   Download

MIT

The Requires

 

by Alban Jubert

database extension yii2 behavior active-record relations active-query has-many has-one

28/10 2017

dev-extra-column-junction-table

dev-extra-column-junction-table

Validate and save automatically related Active Record models.

  Sources   Download

MIT

The Requires

 

by Alban Jubert

database extension yii2 behavior active-record relations active-query has-many has-one

28/10 2017

1.3.1

1.3.1.0

Validate and save automatically related Active Record models.

  Sources   Download

MIT

The Requires

 

by Alban Jubert

database extension yii2 behavior active-record relations active-query has-many has-one

12/10 2017

1.3.0

1.3.0.0

Validate and save automatically related Active Record models.

  Sources   Download

MIT

The Requires

 

by Alban Jubert

database extension yii2 behavior active-record relations active-query has-many has-one

08/04 2017

1.2.0

1.2.0.0

Validate and save automatically related Active Record models.

  Sources   Download

MIT

The Requires

 

by Alban Jubert

database extension yii2 behavior active-record relations active-query has-many has-one

04/03 2017

1.1.3

1.1.3.0

Validate and save automatically related Active Record models.

  Sources   Download

MIT

The Requires

 

by Alban Jubert

database extension yii2 behavior active-record relations active-query has-many has-one

29/11 2016

1.1.2

1.1.2.0

Validate and save automatically related Active Record models.

  Sources   Download

MIT

The Requires

 

by Alban Jubert

database extension yii2 behavior active-record relations active-query has-many has-one

28/11 2016

1.1.1

1.1.1.0

Validate and save automatically related Active Record models.

  Sources   Download

MIT

The Requires

 

by Alban Jubert

database extension yii2 behavior active-record relations active-query has-many has-one

24/11 2016

1.1.0

1.1.0.0

Validate and save automatically related Active Record models.

  Sources   Download

MIT

The Requires

 

by Alban Jubert

database extension yii2 behavior active-record relations active-query has-many has-one

03/04 2016

1.0.2

1.0.2.0

Validate and save automatically related Active Record models.

  Sources   Download

MIT

The Requires

 

by Alban Jubert

database extension yii2 behavior active-record relations active-query has-many has-one

02/04 2016

1.0.1

1.0.1.0

Validate and save automatically related Active Record models.

  Sources   Download

MIT

The Requires

 

by Alban Jubert

database extension yii2 behavior active-record relations active-query has-many has-one

26/03 2016

1.0.0

1.0.0.0

Validate and save automatically related Active Record models.

  Sources   Download

MIT

The Requires

 

by Alban Jubert

database extension yii2 behavior active-record relations active-query has-many has-one