PHPackages                             vadymsemeniuk/yii2-many-to-many-ar-level-save-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. [Database &amp; ORM](/categories/database)
4. /
5. vadymsemeniuk/yii2-many-to-many-ar-level-save-behavior

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

vadymsemeniuk/yii2-many-to-many-ar-level-save-behavior
======================================================

Behavior for saving many to many relation

082.9k—1.8%1PHP

Since Mar 15Pushed 1y ago1 watchersCompare

[ Source](https://github.com/vadimsemenykv/yii2-many-to-many-ar-level-save-behavior)[ Packagist](https://packagist.org/packages/vadymsemeniuk/yii2-many-to-many-ar-level-save-behavior)[ RSS](/packages/vadymsemeniuk-yii2-many-to-many-ar-level-save-behavior/feed)WikiDiscussions master Synced 1mo ago

READMEChangelogDependenciesVersions (3)Used By (0)

[![Total Downloads](https://camo.githubusercontent.com/8ed454c98c01d341a0365d5d3fc66200fd0d727311b90593266fd06a0a558dde/68747470733a2f2f706f7365722e707567782e6f72672f766164796d73656d656e69756b2f796969322d6d616e792d746f2d6d616e792d61722d6c6576656c2d736176652d6265686176696f722f642f746f74616c2e706e67)](https://packagist.org/packages/vadymsemeniuk/yii2-many-to-many-ar-level-save-behavior)[![Latest Stable Version](https://camo.githubusercontent.com/041f422c536875799e2f4e6318eb3daf2f61304cefd60aa7885d7a064efbb143/68747470733a2f2f706f7365722e707567782e6f72672f766164796d73656d656e69756b2f796969322d6d616e792d746f2d6d616e792d61722d6c6576656c2d736176652d6265686176696f722f762f737461626c652e706e67)](https://packagist.org/packages/vadymsemeniuk/yii2-many-to-many-ar-level-save-behavior)[![Dependency Status](https://camo.githubusercontent.com/5573e267171598f6a1b8c46c81f65492c3a048e1b74f631107ede757a839e36c/68747470733a2f2f7777772e76657273696f6e6579652e636f6d2f7068702f766164796d73656d656e69756b3a796969322d6d616e792d746f2d6d616e792d61722d6c6576656c2d736176652d6265686176696f722f6465762d6d61737465722f62616467653f7374796c653d666c6174)](https://www.versioneye.com/php/vadymsemeniuk:yii2-many-to-many-ar-level-save-behavior)

Yii2 ManyToMany Active Record Level Behavior
============================================

[](#yii2-manytomany-active-record-level-behavior)

Extension save many-to-many related data

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

[](#installation)

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

Either run

```
php composer.phar require --prefer-dist vadymsemeniuk/yii2-many-to-many-ar-level-save-behavior "*"

```

or add

```
"vadymsemeniuk/yii2-many-to-many-ar-level-save-behavior": "*"

```

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

Usage
-----

[](#usage)

An example of usage could be:

Suppose you have the following schema.

```
CREATE TABLE `article` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `label` varchar(1024) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`id`),
);

CREATE TABLE `tag` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `label` varchar(1024) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`id`),
);

CREATE TABLE `article_to_tag` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `article_id` int(11) NOT NULL,
  `tag_id` int(11) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `fk-article_to_tag-article_id-article-id` (`article_id`),
  KEY `fk-article_to_tag-tag_id-tag-id` (`tag_id`),
  CONSTRAINT `fk-article_to_tag-article_id-article-id` FOREIGN KEY (`article_id`) REFERENCES `article` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `fk-article_to_tag-tag_id-tag-id` FOREIGN KEY (`tag_id`) REFERENCES `tag` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
)
```

Your code must look like this

```
use vadymsemenykv\manyToManyBehavior\ManyToManyArLevelSaveBehavior

/**
 * @ property Tag[] $tags
 */
class Article extends ActiveRecord {
    public $tagIds = [];

    public function tableName() {
        return 'article';
    }

    public function getTags()
    {
        return $this->hasMany(Tag::className(), ['id' => 'tag_id'])
            ->viaTable('article_to_tag', ['article_id' => 'id']);
    }

    public function behaviors()
    {
        return [
            'manyToManyBehavior' => [
                'class' => ManyToManyArLevelSaveBehavior::className(),
                'relations' => [
                    'tags' => [
                        'modelClass' => Tag::className(),
                        'attribute' => 'tagIds',
                        'pkColumnName' => 'id',
                        'deleteAllRelatedEntriesBeforeSave' => true,
                    ],
                ],
            ],
        ];
    }
}
```

```
class Tag extends ActiveRecord {

    public function tableName() {
        return 'tag';
    }
}
```

```
$tag = new Tag();
$tag->id = 1;
$tag->label = 'Tag #1';
$tag->save();

$tag = new Tag();
$tag->id = 2;
$tag->label = 'Tag #2';
$tag->save();

$article = new Article();
$article->label = 'New article';
$article->tagIds = [1, 2];
$article->save();

$tags = $article->tags;

/**
 *  $tags = [
 *     0 => object(Tag)
 *          ...
 *          private '_attributes' (yii\db\BaseActiveRecord) =>
 *                  'id' => int 1
 *                  'label' => string 'Tag #1'
 *          ...
 *     1 => object(Tag)
 *          ...
 *          private '_attributes' (yii\db\BaseActiveRecord) =>
 *                  'id' => int 2
 *                  'label' => string 'Tag #2'
 *          ...
 *  ]
 */
```

Advanced usage
--------------

[](#advanced-usage)

For example, if in table `article_to_tag` in example above present `type_id` column with some additional identifier - config for behavior may be like this:

```
public function behaviors()
{
    return [
        'manyToManyBehavior' => [
            'class' => ManyToManyArLevelSaveBehavior::className(),
            'relations' => [
                'tags' => [
                    'modelClass' => Tag::className(),
                    'attribute' => 'tagIds',
                    'pkColumnName' => 'id',
                    'deleteAllRelatedEntriesBeforeSave' => true,
                    'extraColumns' => [
                        'type_id' => ArticleToTag::TYPE_1
                    ],
                    'additionalUnlinkCondition' => [
                        'type_id' => ArticleToTag::TYPE_1,
                    ]
                ],
            ],
        ],
    ];
}

```

where `extraColumns` will be used in link() method, and `additionalUnlinkCondition` will be merged with unlink condition.

###  Health Score

32

—

LowBetter than 72% of packages

Maintenance30

Infrequent updates — may be unmaintained

Popularity32

Limited adoption so far

Community10

Small or concentrated contributor base

Maturity44

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 85.7% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

### Community

Maintainers

![](https://www.gravatar.com/avatar/3d050fe29a9bdad7efe48b89e5bccdb1252958d86382021dc4b6f2e2a88e3603?d=identicon)[Vadym Semeniuk](/maintainers/Vadym%20Semeniuk)

---

Top Contributors

[![vadimsemenykv](https://avatars.githubusercontent.com/u/8122660?v=4)](https://github.com/vadimsemenykv "vadimsemenykv (6 commits)")[![athl64](https://avatars.githubusercontent.com/u/4989972?v=4)](https://github.com/athl64 "athl64 (1 commits)")

### Embed Badge

![Health badge](/badges/vadymsemeniuk-yii2-many-to-many-ar-level-save-behavior/health.svg)

```
[![Health](https://phpackages.com/badges/vadymsemeniuk-yii2-many-to-many-ar-level-save-behavior/health.svg)](https://phpackages.com/packages/vadymsemeniuk-yii2-many-to-many-ar-level-save-behavior)
```

###  Alternatives

[doctrine/orm

Object-Relational-Mapper for PHP

10.2k285.3M6.2k](/packages/doctrine-orm)[jdorn/sql-formatter

a PHP SQL highlighting library

3.9k115.1M102](/packages/jdorn-sql-formatter)[illuminate/database

The Illuminate Database package.

2.8k52.4M9.4k](/packages/illuminate-database)[ramsey/uuid-doctrine

Use ramsey/uuid as a Doctrine field type.

90440.3M211](/packages/ramsey-uuid-doctrine)[reliese/laravel

Reliese Components for Laravel Framework code generation.

1.7k3.4M16](/packages/reliese-laravel)[wildside/userstamps

Laravel Userstamps provides an Eloquent trait which automatically maintains `created\_by` and `updated\_by` columns on your model, populated by the currently authenticated user in your application.

7511.7M13](/packages/wildside-userstamps)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
