A reusable and robust behavior for managing many-to-many (M2M) relationships in Yii2 ActiveRecord using virtual attributes.
๐งฉ Inspired by the archived
yii2tech/ar-linkmany
package by Paul Klimov, now extended with modern improvements, full test coverage, and long-term support.
composer require jonatas-sas/yii2-m2m-behavior
- ๐ English Docs
- ๐ง๐ท Documentaรงรฃo em Portuguรชs
Yii2 Many to Many Behavior helps you:
- Manage M2M relations using virtual attributes (e.g.
tagIds
). - Automatically sync relations on
insert
,update
, anddelete
. - Control deletion of junction table rows (
deleteOnUnlink
). - Add extra columns to junction records (e.g. timestamps or metadata).
- Integrate smoothly into ActiveForm, GridView, and DetailView.
use yii\db\ActiveRecord;
use yii\db\ActiveQuery;
use odara\yii\behaviors\LinkManyToManyBehavior;
/**
* @property int $id
* @property string $name
*
* @property-read Tag[] $tags
* @property int[] $tagIds
*/
class Item extends ActiveRecord
{
/**
* @inheritdoc
*/
public function behaviors()
{
return [
'tags' => [
'class' => LinkManyToManyBehavior::class,
'relation' => 'tags',
'referenceAttribute' => 'tagIds',
'deleteOnUnlink' => true,
'extraColumns' => [
'source' => 'admin',
'created_at' => static fn (): int => time(),
],
],
];
}
/**
* Returns the relation between Item and Tag models.
*
* @return ActiveQuery
*/
public function getTags(): ActiveQuery
{
return $this->hasMany(Tag::class, ['id' => 'tag_id'])
->viaTable('item_tag', ['item_id' => 'id']);
}
}
echo $form->field($model, 'tagIds')->checkboxList(
Tag::find()
->select(['name', 'id'])
->indexBy('id')
->column()
);
Found a bug or want to suggest an improvement?
- Read the Contributing Guide
- Follow PSR-12 and Yii2 coding practices
Yii2 Many to Many Behavior is released under the MIT License.
Maintained by the Yii2 community.
Inspired by the Yii2Tech package and rebuilt with care for modern development.