PHPackages                             antonyz89/yii2-many-to-many - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Validation &amp; Sanitization](/categories/validation)
4. /
5. antonyz89/yii2-many-to-many

ActiveYii2-extension[Validation &amp; Sanitization](/categories/validation)

antonyz89/yii2-many-to-many
===========================

Many-to-many ActiveRecord relation for Yii 2 framework. Created By Alexey Rogachev, forked by AntonyZ89

0.3.6(2y ago)01.6k↓87.5%11BSD-3-ClausePHP

Since Apr 12Pushed 2y ago1 watchersCompare

[ Source](https://github.com/AntonyZ89/yii2-many-to-many)[ Packagist](https://packagist.org/packages/antonyz89/yii2-many-to-many)[ Docs](https://github.com/arogachev/yii2-many-to-many)[ RSS](/packages/antonyz89-yii2-many-to-many/feed)WikiDiscussions master Synced today

READMEChangelog (6)Dependencies (3)Versions (11)Used By (1)

Yii 2 Many-to-many
==================

[](#yii-2-many-to-many)

Implementation of [Many-to-many relationship](http://en.wikipedia.org/wiki/Many-to-many_%28data_model%29)for Yii 2 framework.

**Created by [arogachev](https://github.com/arogachev), forked by [AntonyZ89](https://github.com/AntonyZ89)**

[![Latest Stable Version](https://camo.githubusercontent.com/f6dc793c21b581aaa6799da3f1b9721f31414adc38b068df2ff6a954a1047992/68747470733a2f2f706f7365722e707567782e6f72672f616e746f6e797a38392f796969322d6d616e792d746f2d6d616e792f762f737461626c65)](https://packagist.org/packages/antonyz89/yii2-many-to-many)[![Total Downloads](https://camo.githubusercontent.com/35587525f202d6a13e444c3986a1fdaaf1a73225b4af3ef7eb731f32186cd950/68747470733a2f2f706f7365722e707567782e6f72672f616e746f6e797a38392f796969322d6d616e792d746f2d6d616e792f646f776e6c6f616473)](https://packagist.org/packages/antonyz89/yii2-many-to-many)[![Latest Unstable Version](https://camo.githubusercontent.com/5bb22677e0e7a5cf08b4d44c0003a612feb90feeb56507dd71b02e9e94f2ce89/68747470733a2f2f706f7365722e707567782e6f72672f616e746f6e797a38392f796969322d6d616e792d746f2d6d616e792f762f756e737461626c65)](https://packagist.org/packages/antonyz89/yii2-many-to-many)[![License](https://camo.githubusercontent.com/3e8bc43fc1458392598fe87f48f8f7202c6b424437e2c895cdf9986439e3049c/68747470733a2f2f706f7365722e707567782e6f72672f61726f6761636865762f796969322d6d616e792d746f2d6d616e792f6c6963656e7365)](https://packagist.org/packages/arogachev/yii2-many-to-many)

- [Yii 2 Many-to-many](#yii-2-many-to-many)
    - [Installation](#installation)
    - [Features](#features)
    - [Creating editable attribute](#creating-editable-attribute)
    - [Attaching and configuring behavior](#attaching-and-configuring-behavior)
    - [Attribute validation](#attribute-validation)
    - [Adding control to view](#adding-control-to-view)

Installation
------------

[](#installation)

The preferred way to install this extension is through [composer](http://getcomposer.org/download/).

Either run

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

```

or add

```
"antonyz89/yii2-many-to-many": "0.3.*"

```

to the require section of your `composer.json` file.

Features
--------

[](#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
---------------------------

[](#creating-editable-attribute)

Simply add public property to your `ActiveRecord` model like this:

```
/** @var int[] */
public $editableRoles = [];
```

It will store primary keys of related records during update.

Attaching and configuring behavior
----------------------------------

[](#attaching-and-configuring-behavior)

First way is to explicitly specify all parameters:

```
namespace common\models;

use antonyz89\ManyToMany\behaviors\ManyToManyBehavior;

class User extends ActiveRecord {

    /** @var int[] */
    public $editableRoles = [];

    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            [
                'class' => ManyToManyBehavior::class,
                'autoFill' => true # default is true. If false, you should fill manually with $model->fill() method
                'relations' => [
                    [
                        // Editable attribute name
                        'editableAttribute' => 'editableRoles',
                        // Model of the junction table
                        'modelClass' => UserRole::class,
                        // Name of the column in junction table that represents current model
                        'ownAttribute' => 'user_id',
                        // Related model class
                        'relatedModel' => Role::class,
                        // Name of the column in junction table that represents related model
                        'relatedAttribute' => 'role_id',
                    ],
                ],
            ],
        ];
    }
}
```

Attribute validation
--------------------

[](#attribute-validation)

Add editable attribute to model rules for massive assignment.

```
public function rules()
{
    ['editableRoles', 'required'],
    ['editableRoles', 'integer'],
    ['editableRoles', 'each', 'skipOnEmpty' => false, 'rule' => [
        'exist', 'skipOnError' => true, 'targetClass' => Role::class, 'targetAttribute' => ['editableRoles' => 'id']
    ]],
}
```

Or use custom validator:

```
use antonyz89\ManyToMany\validators\ManyToManyValidator;

public function rules()
{
    ['editableRoles', ManyToManyValidator::class],
}
```

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

[](#adding-control-to-view)

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

```
