https://github.com/frostealth/yii2-relation-behavior
Easy linking and sync relationships many-to-many and one-to-many
https://github.com/frostealth/yii2-relation-behavior
sync-relationships yii2 yii2-behaviors
Last synced: 3 months ago
JSON representation
Easy linking and sync relationships many-to-many and one-to-many
- Host: GitHub
- URL: https://github.com/frostealth/yii2-relation-behavior
- Owner: frostealth
- License: mit
- Created: 2015-11-06T22:08:41.000Z (over 9 years ago)
- Default Branch: master
- Last Pushed: 2016-04-12T11:07:43.000Z (about 9 years ago)
- Last Synced: 2025-01-31T09:22:16.953Z (4 months ago)
- Topics: sync-relationships, yii2, yii2-behaviors
- Language: PHP
- Homepage:
- Size: 8.79 KB
- Stars: 4
- Watchers: 2
- Forks: 2
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE.md
Awesome Lists containing this project
README
# Yii2 Relation Behavior
Easy linking and sync relationships many-to-many.
## Installation
Run the [Composer](http://getcomposer.org/download/) command to install the latest stable version:
```
composer require frostealth/yii2-relation-behavior @stable
```## Behaviors
* `SyncRelationBehavior`
* `EasyRelationBehavior`## Usage
### SyncRelationBehavior
Attach the behavior to your model:
```php
public function behaviors()
{
return [
SyncRelationBehavior::className(),
];
}
```Use the `sync` method to construct many-to-many associations.
The `sync` method accepts an array of IDs.```php
$model->sync('categories', [2, 5, 9]);
```### EasyRelationBehavior
The `EasyRelationBehavior` extends the `SyncRelationBehavior`.
Attach the behavior to your model:
```php
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:
```php
$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:
```php
all(), 'id', 'name') ?>
= $form->field($model, 'categoriesIds')->dropDownList($categories, ['multiple' => true]) ?>
```## License
The MIT License (MIT).
See [LICENSE.md](https://github.com/frostealth/yii2-relation-behavior/blob/master/LICENSE.md) for more information.