PHPackages                             ed-smartass/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. [Database &amp; ORM](/categories/database)
4. /
5. ed-smartass/yii2-relation-behavior

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

ed-smartass/yii2-relation-behavior
==================================

Behavior for gettting and saving ActiveRecord relations

1.0.3(3y ago)2172—0%MITPHP

Since Aug 28Pushed 3y ago1 watchersCompare

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

READMEChangelog (3)Dependencies (1)Versions (5)Used By (0)

yii2-relation-behavior
======================

[](#yii2-relation-behavior)

### Installation

[](#installation)

```
composer require ed-smartass/yii2-relation-behavior

```

### Example

[](#example)

```
use Smartass\Yii2RelationBehavior\RelationBehavior;

// ...

/**
 * @inheritdoc
 */
public function behaviors()
{
    return [
        // ...
        'relation' => [
            'class' => RelationBehavior::class,
            'relations' => [
                // Many to one relation
                'manufacturer' => [
                    'target' => Manufacturer::class,
                    'link' => ['manufacturer_id' => 'manufacturer_id']
                ],
                // One to many relation
                'modelCategories' => [
                    'target' => ModelCategories::class,
                    'link' => ['model_id' => 'model_id'],
                    'multiple' => true
                ],
                // Many to many relation
                'categories' => [
                    'target' => Category::class,
                    'link' => ['category_id' => 'category_id'],
                    'multiple' => true,
                    'via' => 'modelCategories'
                ]
            ]
        ]
        // ...
    ];
}

// ...
```

### Relation settings

[](#relation-settings)

- **target** — target class

    - Type: `string`
    - Required: `true`
- **link** — link condition (same as native yii2 declaration)

    - Type: `array`
    - Required: `true`
- **multiple** — is multiple relation or not (if `true` relation will be like `$this->hasMany(...)` overwise `$this->hasOne(...)`)

    - Type: `bool`
    - Required: `false`
    - Default: `false`
- **onCondition** — linking condition (will expand to `$this->hasMany(...)->onCondition(['status' => Category::STATUS_ACTIVE])`)

    - Type: `array|null`
    - Required: `false`
    - Default: `null`
- **filter** — extra linking filter

    - Type: `array|string|Closure|null`
    - Required: `false`
    - Default: `null`
- **via** — name of junction relation (will expand to `$this->hasMany(...)->via(...)`)

    - Type: `string|null`
    - Required: `false`
    - Default: `false`
- **extraColumns** — extra column for linking many to many relations

    - Type: `array|null`
    - Required: `false`
    - Default: `[]`
- **find** - Callback for searching related record from array (if you set relation value `$model->manufacturer = ['manufacturer_id' => 12]`)

    - Type: `Closure|null`
    - Required: `false`
    - Default: `Closure` (Searching by all pk keys)

### How to use

[](#how-to-use)

This behavior will allow you to use related models like usuall without created extra methods like:

```
public function getCategories()
{
    return $this->hasMany(...);
}
```

Instead, you just need to declare this in the behavior like on example.\_\_ In addition, this behavior can create or save changes to the related model. To do this, behavior uses a transaction. So you can do this:

```
$model->categories = [
    ['category_id' => 1], // Will find (or create if not exists) category with category_id `1`
    ['category_id' => 2, 'name' => 'New name'], // Will find (or create) category with category_id `1` and change name
    ['name' => 'New category'] // Will create new category
];
$model->save();
```

**Each related model will be validated before saving. If it fails, the transaction will be canceled.**\_\_ **Don't foget add relations to model `rules` as `safe`**

```
/**
 * @inheritdoc
 */
public function rules()
{
    return [
        // ...
        ['categories', 'safe'],
        // ...
    ];
}
```

### Limitation

[](#limitation)

This behavior will successfully save only truly basic relations

- One to many
- Many to one
- Many to many

###  Health Score

27

—

LowBetter than 49% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity15

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity54

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% 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.

###  Release Activity

Cadence

Every ~89 days

Total

4

Last Release

1449d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/dfbc1cfb2ad235a55d89d24c99f2e9a772eb62974d2cfdd61f15b973aacfe67f?d=identicon)[ed-smartass](/maintainers/ed-smartass)

---

Top Contributors

[![ed-smartass](https://avatars.githubusercontent.com/u/62896221?v=4)](https://github.com/ed-smartass "ed-smartass (6 commits)")

---

Tags

yii2yii2-behaviorrelation behavior

### Embed Badge

![Health badge](/badges/ed-smartass-yii2-relation-behavior/health.svg)

```
[![Health](https://phpackages.com/badges/ed-smartass-yii2-relation-behavior/health.svg)](https://phpackages.com/packages/ed-smartass-yii2-relation-behavior)
```

###  Alternatives

[voskobovich/yii2-linker-behavior

This behavior makes it easy to maintain many-to-many and one-to-many relations in your ActiveRecord models.

80319.0k9](/packages/voskobovich-yii2-linker-behavior)[yii2tech/illuminate

Yii2 to Laravel Migration Package

11315.1k](/packages/yii2tech-illuminate)[mootensai/yii2-relation-trait

Yii 2 Models load with relation, &amp; transaction save with relation

47220.3k9](/packages/mootensai-yii2-relation-trait)[nhkey/yii2-activerecord-history

Storage history of changes to ActiveRecord

46143.4k1](/packages/nhkey-yii2-activerecord-history)[dmstr/yii2-db

Database extensions

19618.8k6](/packages/dmstr-yii2-db)[spanjeta/yii2-backup

Database Backup and Restore functionality

285.0k1](/packages/spanjeta-yii2-backup)

PHPackages © 2026

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