PHPackages                             yii2tech/ar-linkmany - 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. [Database &amp; ORM](/categories/database)
4. /
5. yii2tech/ar-linkmany

AbandonedArchivedYii2-extension[Database &amp; ORM](/categories/database)

yii2tech/ar-linkmany
====================

Provides support for many-to-many relations saving in Yii2 ActiveRecord

1.0.3(8y ago)85328.2k↓65.2%164BSD-3-ClausePHP

Since Dec 26Pushed 7y ago1 watchersCompare

[ Source](https://github.com/yii2tech/ar-linkmany)[ Packagist](https://packagist.org/packages/yii2tech/ar-linkmany)[ RSS](/packages/yii2tech-ar-linkmany/feed)WikiDiscussions master Synced 2d ago

READMEChangelogDependencies (1)Versions (5)Used By (4)

 [ ![](https://avatars2.githubusercontent.com/u/12951949) ](https://github.com/yii2tech)

ActiveRecord Many-to-Many Saving Extension for Yii2
===================================================

[](#activerecord-many-to-many-saving-extension-for-yii2)

This extension provides support for ActiveRecord many-to-many relation saving. For example: single "item" may belong to several "groups", each group may be linked with several items. Unlike regular \[\[\\yii\\db\\BaseActiveRecord::link()\]\] usage, this extension automatically checks references existence, removes excluded references and provide support for web form composition.

For license information check the [LICENSE](LICENSE.md)-file.

[![Latest Stable Version](https://camo.githubusercontent.com/d7f41fec7eadbb72e7c40c6ff27b99a8934492fc63d05ff37b680df67183bdd0/68747470733a2f2f706f7365722e707567782e6f72672f79696932746563682f61722d6c696e6b6d616e792f762f737461626c652e706e67)](https://packagist.org/packages/yii2tech/ar-linkmany)[![Total Downloads](https://camo.githubusercontent.com/26de34ec830f799a72805d88893ed9c57cbd256aa1063e6e442221e1da31e148/68747470733a2f2f706f7365722e707567782e6f72672f79696932746563682f61722d6c696e6b6d616e792f646f776e6c6f6164732e706e67)](https://packagist.org/packages/yii2tech/ar-linkmany)[![Build Status](https://camo.githubusercontent.com/efc1aedc9913b5c184ead2ac364476c8c670afeaee4d2f899f1dfa1cad4229f8/68747470733a2f2f7472617669732d63692e6f72672f79696932746563682f61722d6c696e6b6d616e792e7376673f6272616e63683d6d6173746572)](https://travis-ci.org/yii2tech/ar-linkmany)

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

[](#installation)

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

Either run

```
php composer.phar require --prefer-dist yii2tech/ar-linkmany

```

or add

```
"yii2tech/ar-linkmany": "*"
```

to the require section of your composer.json.

Usage
-----

[](#usage)

This extension provides support for ActiveRecord many-to-many relation saving. This support is granted via \[\[\\yii2tech\\ar\\linkmany\\LinkManyBehavior\]\] ActiveRecord behavior. You'll need to attach it to your ActiveRecord class and point the target "has-many" relation for it:

```
class Item extends ActiveRecord
{
    public function behaviors()
    {
        return [
            'linkGroupBehavior' => [
                'class' => LinkManyBehavior::className(),
                'relation' => 'groups', // relation, which will be handled
                'relationReferenceAttribute' => 'groupIds', // virtual attribute, which is used for related records specification
            ],
        ];
    }

    public static function tableName()
    {
        return 'Item';
    }

    public function getGroups()
    {
        return $this->hasMany(Group::className(), ['id' => 'groupId'])->viaTable('ItemGroup', ['itemId' => 'id']);
    }
}
```

Being attached \[\[\\yii2tech\\ar\\linkmany\\LinkManyBehavior\]\] adds a virtual proprty to the owner ActiveRecord, which name is determined by \[\[\\yii2tech\\ar\\linkmany\\LinkManyBehavior::$relationReferenceAttribute\]\]. You will be able to specify related models primary keys via this attribute:

```
// Pick up related model primary keys:
$groupIds = Group::find()
    ->select('id')
    ->where(['isActive' => true])
    ->column();

$item = new Item();
$item->groupIds = $groupIds; // setup related models references
$item->save(); // after main model is saved referred related models are linked
```

The above example is equal to the following code:

```
$groups = Group::find()
    ->where(['isActive' => true])
    ->all();

$item = new Item();
$item->save();

foreach ($groups as $group) {
    $item->link('groups', $group);
}
```

> Attention: do NOT declare `relationReferenceAttribute` attribute in the owner ActiveRecord class. Make sure it does not conflict with any existing owner field or virtual property.

Virtual property declared via `relationReferenceAttribute` serves not only for saving. It also contains existing references for the relation:

```
$item = Item::findOne(15);
var_dump($item->groupIds); // outputs something like: array(2, 5, 11)
```

You may as well edit the references list for existing record, while saving linked records will be synchronized:

```
$item = Item::findOne(15);
$item->groupIds = array_merge($item->groupIds, [17, 21]);
$item->save(); // groups "17" and "21" will be added

$item->groupIds = [5];
$item->save(); // all groups except "5" will be removed
```

> Note: if attribute declared by `relationReferenceAttribute` is never invoked for reading or writing, it will not be processed on owner saving. Thus it will not affect pure owner saving.

Creating relation setup web interface
--------------------------------------

[](#creating-relation-setup-web-interface-)

The main purpose of \[\[\\yii2tech\\ar\\linkmany\\LinkManyBehavior::$relationReferenceAttribute\]\] is support for creating many-to-many setup web interface. All you need to do is declare a validation rule for this virtual property in your ActiveRecord, so its value can be collected from the request:

```
class Item extends ActiveRecord
{
    public function rules()
    {
        return [
            ['groupIds', 'safe'] // ensure 'groupIds' value can be collected on `populate()`
            // ...
        ];
    }

    // ...
}
```

Inside the view file you should use `relationReferenceAttribute` property as an attribute name for the form input:

```
