PHPackages                             frostealth/yii2-relation-behavior - 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. [Utility &amp; Helpers](/categories/utility)
4. /
5. frostealth/yii2-relation-behavior

ActiveYii2-extension[Utility &amp; Helpers](/categories/utility)

frostealth/yii2-relation-behavior
=================================

Easy linking and sync relationships many-to-many and one-to-many

0.2.4(10y ago)415.9k↓25%2MITPHPPHP &gt;=5.4.0

Since Nov 6Pushed 10y ago1 watchersCompare

[ Source](https://github.com/frostealth/yii2-relation-behavior)[ Packagist](https://packagist.org/packages/frostealth/yii2-relation-behavior)[ Docs](https://github.com/frostealth/yii2-relation-behavior)[ RSS](/packages/frostealth-yii2-relation-behavior/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (7)Dependencies (2)Versions (8)Used By (0)

Yii2 Relation Behavior
======================

[](#yii2-relation-behavior)

Easy linking and sync relationships many-to-many.

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

[](#installation)

Run the [Composer](http://getcomposer.org/download/) command to install the latest stable version:

```
composer require frostealth/yii2-relation-behavior @stable

```

Behaviors
---------

[](#behaviors)

- `SyncRelationBehavior`
- `EasyRelationBehavior`

Usage
-----

[](#usage)

### SyncRelationBehavior

[](#syncrelationbehavior)

Attach the behavior to your model:

```
public function behaviors()
{
    return [
        SyncRelationBehavior::className(),
    ];
}
```

Use the `sync` method to construct many-to-many associations. The `sync` method accepts an array of IDs.

```
$model->sync('categories', [2, 5, 9]);
```

### EasyRelationBehavior

[](#easyrelationbehavior)

The `EasyRelationBehavior` extends the `SyncRelationBehavior`.

Attach the behavior to your model:

```
public function behaviors()
{
    return [
        [
            'class' => EasyRelationBehavior::className(),
            'relations' => ['categories'],
            'suffix' => 'ids', // by default
        ],
    ];
}

public function rules()
{
    return [
        ['categoriesIds', 'each', 'rule' => ['integer', 'integerOnly' => true]],
    ];
}
```

Just add your `$suffix` to the relation name and you will get associated ids:

```
$categoriesIds = $model->categoriesIds; // [1, 3, 4]

// linking
$categoriesIds = [2, 3, 5];
$model->categoriesIds = $categoriesIds;
$model->save();
```

Add control to view for managing related list.

Without extensions it can be done with multiple select:

```
