All Projects → arogachev → Yii2 Many To Many

arogachev / Yii2 Many To Many

Licence: other
Implementation of Many-to-many relationship for Yii 2 framework

Projects that are alternatives of or similar to Yii2 Many To Many

Yii2 Helpers
Collection of useful helper functions for Yii Framework 2.0
Stars: ✭ 16 (-46.67%)
Mutual labels:  yii2, yii2-extension
collection
Basic collection library for Yii Framework 2.0
Stars: ✭ 29 (-3.33%)
Mutual labels:  yii2, yii2-extension
yii2-firebird
Firebird connector for Yii2 framework
Stars: ✭ 23 (-23.33%)
Mutual labels:  yii2, yii2-extension
Yii2 Selectize
selectize.js wrapper for yii2.
Stars: ✭ 18 (-40%)
Mutual labels:  yii2, yii2-extension
Yii2 Slack Log
Pretty Slack log target for Yii 2
Stars: ✭ 24 (-20%)
Mutual labels:  yii2, yii2-extension
Yii2 Elfinder
elFinder file manager for Yii 2
Stars: ✭ 21 (-30%)
Mutual labels:  yii2, yii2-extension
yii2-blog
Simple, configurable blog module for Yii2 (post, comment, nested category, tags). + frontend, backend. + SEO! (Opengraph, Schema.org) ~~~COMING SOON V2.0~~~ Please STAR this repo
Stars: ✭ 79 (+163.33%)
Mutual labels:  yii2, yii2-extension
yii2-merit
Reputation engine for Yii2 用于实现积分,等级功能的设计
Stars: ✭ 16 (-46.67%)
Mutual labels:  yii2, yii2-extension
Yii2 C3 Chart
Yii2 wrapper for D3-based reusable chart library
Stars: ✭ 9 (-70%)
Mutual labels:  yii2, yii2-extension
Yii2 Gentelella
Free admin template for backend
Stars: ✭ 266 (+786.67%)
Mutual labels:  yii2, yii2-extension
yii2-facades
Facades for Yii 2
Stars: ✭ 21 (-30%)
Mutual labels:  yii2, yii2-extension
Yii2 Telegram Log
Telegram log target for Yii 2
Stars: ✭ 24 (-20%)
Mutual labels:  yii2, yii2-extension
yii2-star-rating
Star rating widget based on jQuery Raty
Stars: ✭ 16 (-46.67%)
Mutual labels:  yii2, yii2-extension
Yii2 Google Maps Markers
Google Maps Markers Widget for Yii2
Stars: ✭ 16 (-46.67%)
Mutual labels:  yii2, yii2-extension
yii2-telegram
Support chat for site based on Telegram bot
Stars: ✭ 49 (+63.33%)
Mutual labels:  yii2, yii2-extension
yii2-jwt-user
JWT (JSON Web Token) User component for Yii 2
Stars: ✭ 16 (-46.67%)
Mutual labels:  yii2, yii2-extension
yii2-tinymce
Yii2 extension, tinymce wysiwyg editor
Stars: ✭ 16 (-46.67%)
Mutual labels:  yii2, yii2-extension
filedb
ActiveRecord for static data definitions based on files
Stars: ✭ 72 (+140%)
Mutual labels:  yii2, yii2-extension
yii2-queuemanager
Yii2 Queue Manager (Analytic & Monitor)
Stars: ✭ 18 (-40%)
Mutual labels:  yii2, yii2-extension
Yii2 User
[ABANDONED] Flexible user registration and authentication module for Yii2
Stars: ✭ 946 (+3053.33%)
Mutual labels:  yii2, yii2-extension

Yii 2 Many-to-many

Implementation of Many-to-many relationship for Yii 2 framework.

Latest Stable Version Total Downloads Latest Unstable Version License

Installation

The preferred way to install this extension is through composer.

Either run

php composer.phar require --prefer-dist arogachev/yii2-many-to-many

or add

"arogachev/yii2-many-to-many": "0.2.*"

to the require section of your composer.json file.

Features

  • Configuring using existing hasMany relations
  • Multiple relations
  • No extra queries. For example, if initially model has 100 related records, after adding just one, exactly one row will be inserted. If nothing was changed, no queries will be executed.
  • Auto filling of editable attribute
  • Validator for checking if the received list is valid

Creating editable attribute

Simply add public property to your ActiveRecord model like this:

/**
 * @var array
 */
public $editableUsers = [];

It will store primary keys of related records during update.

Attaching and configuring behavior

First way is to explicitly specify all parameters:

use arogachev\ManyToMany\behaviors\ManyToManyBehavior;

/**
 * @inheritdoc
 */
public function behaviors()
{
    return [
        [
            'class' => ManyToManyBehavior::className(),
            'relations' => [
                [
                    'editableAttribute' => 'editableUsers', // Editable attribute name
                    'table' => 'tests_to_users', // Name of the junction table
                    'ownAttribute' => 'test_id', // Name of the column in junction table that represents current model
                    'relatedModel' => User::className(), // Related model class
                    'relatedAttribute' => 'user_id', // Name of the column in junction table that represents related model
                ],
            ],
        ],
    ];
}

But more often we also need to display related models, so it's better to define relation for that and use it for both display and behavior configuration. Both ways (via and viaTable) are considered valid:

Using viaTable:

/**
 * @return \yii\db\ActiveQuery
 */
public function getUsers()
{
    return $this->hasMany(User::className(), ['id' => 'user_id'])
        ->viaTable('tests_to_users', ['test_id' => 'id'])
        ->orderBy('name');
}

Using via (requires additional model for junction table):

/**
 * @return \yii\db\ActiveQuery
 */
public function getTestUsers()
{
    return $this->hasMany(TestUser::className(), ['test_id' => 'id']);
}

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

Order is not required.

Then just pass the name of this relation and all other parameters will be fetched automatically.

/**
 * @inheritdoc
 */
public function behaviors()
{
    return [
        [
            'class' => ManyToManyBehavior::className(),
            'relations' => [
                [
                    'name' => 'users',
                    // This is the same as in previous example
                    'editableAttribute' => 'editableUsers',
                ],
            ],
        ],
    ];
}

Additional many-to-many relations can be added exactly the same. Note that even for one relation you should declare it as a part of relations section.

Filling relations

By default, editableAttribute of each found model will be populated with ids of related models (eager loading is used). If you want more manual control, prevent extra queries, disable autoFill option:

'autoFill' => false,

and fill it only when it's needed, for example in update action of controller. This is recommended way of using.

public function actionUpdate($id)
{
    $model = $this->findModel($id);
    $model->getManyToManyRelation('users')->fill();
    // ...
}

Alternatively you can specify conditions of filling in closure:

'autoFill' => function ($model) {
    return $model->scenario == Test::SCENARIO_UPDATE; // boolean value
}

Even it's possible to do something like this:

'autoFill' => function ($model) {
    return Yii::$app->controller->route == 'tests/default/update';
}

but it's not recommended for usage because model is not appropriate place for handling routes.

Saving relations without massive assignment

When creating model:

$model = new Test;
$model->editableUsers = [1, 2];
$model->save();

When updating model ('autoFill' => true):

$model = new Test;
$model->editableUsers = [1, 2];
$model->save();

When updating model ('autoFill' => false, manual filling):

$model = new Test;
$model->getManyToManyRelation('users')->fill();
var_dump($model->editableUsers) // [1, 2]
$model->editableUsers = [1, 2, 3];
$model->save();

When updating model ('autoFill' => false, without manual filling):

$model = new Test;
var_dump($model->editableUsers) // empty array
$model->save();

In this case many-to-many relations will stay untouched.

Adding attribute as safe

Add editable attribute to model rules for massive assignment.

Either mark it as safe at least:

public function rules()
{
    ['editableUsers', 'safe'],
}

Or use custom validator:

use arogachev\ManyToMany\validators\ManyToManyValidator;

public function rules()
{
    ['editableUsers', ManyToManyValidator::className()],
}

Validator checks list for being array and containing only primary keys presented in related model. It can not be used without attaching ManyToManyBehavior.

Adding control to view

Add control to view for managing related list. Without extensions it can be done with multiple select:

<?= $form->field($model, 'editableUsers')->dropDownList(User::getList(), ['multiple' => true]) ?>

Example of getList() method contents (it needs to be placed in User model):

use yii\helpers\ArrayHelper;

/**
 * @return array
 */
public static function getList()
{
    $models = static::find()->orderBy('name')->all();

    return ArrayHelper::map($models, 'id', 'name');
}

Relation features

You can access many-to-many relation like so:

$relation = $model->getManyToManyRelation('users');

users can be value of either name or table relation property specified in config.

You can fill editableAttribute with ids of related records like so:

$model->getManyToManyRelation('users')->fill();

You can get added and deleted primary keys of related models for specific relation like so:

$addedPrimaryKeys = $model->getManyToManyRelation('users')->getAddedPrimaryKeys();
$deletedPrimaryKeys = $model->getManyToManyRelation('users')->getDeletedPrimaryKeys();

Note that they are only available after the model was saved so you can access it after $model->save() call or in afterSave() event handler.

Running tests

Install dependencies:

composer install

Add database config (tests/config/db-local.php file) with following contents:

<?php

return [
    'class' => 'yii\db\Connection',
    'dsn' => 'mysql:host=localhost;dbname=yii2_many_to_many',
    'username' => 'root',
    'password' => '',
];

You can change dbname, username and password how you want. Make sure create database and user before running tests.

Run tests:

vendor/bin/phpunit
Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].