frostealth / yii2-relation-behavior
Easy linking and sync relationships many-to-many and one-to-many
Installs: 11 905
Dependents: 0
Suggesters: 0
Security: 0
Stars: 4
Watchers: 2
Forks: 2
Open Issues: 0
Type:yii2-extension
Requires
- php: >=5.4.0
- frostealth/php-data-storage: ~2.0
- yiisoft/yii2: ~2.0
This package is not auto-updated.
Last update: 2024-11-05 05:03:30 UTC
README
Easy linking and sync relationships many-to-many.
Installation
Run the Composer 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:
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
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:
<?php $categories = ArrayHelper::map(Category::find()->all(), 'id', 'name') ?> <?= $form->field($model, 'categoriesIds')->dropDownList($categories, ['multiple' => true]) ?>
License
The MIT License (MIT). See LICENSE.md for more information.