frostealth / yii2-relation-behavior
轻松实现多对多和一对多关系的链接和同步
0.2.4
2016-04-12 11:05 UTC
Requires
- php: >=5.4.0
- frostealth/php-data-storage: ~2.0
- yiisoft/yii2: ~2.0
This package is not auto-updated.
Last update: 2024-09-24 04:30:22 UTC
README
轻松实现多对多关系的链接和同步。
安装
运行Composer命令以安装最新稳定版本
composer require frostealth/yii2-relation-behavior @stable
行为
SyncRelationBehavior
EasyRelationBehavior
用法
SyncRelationBehavior
将行为附加到您的模型
public function behaviors() { return [ SyncRelationBehavior::className(), ]; }
使用sync
方法构建多对多关联。该sync
方法接受一个ID数组。
$model->sync('categories', [2, 5, 9]);
EasyRelationBehavior
EasyRelationBehavior
扩展了SyncRelationBehavior
。
将行为附加到您的模型
public function behaviors() { return [ [ 'class' => EasyRelationBehavior::className(), 'relations' => ['categories'], 'suffix' => 'ids', // by default ], ]; } public function rules() { return [ ['categoriesIds', 'each', 'rule' => ['integer', 'integerOnly' => true]], ]; }
只需将您的$suffix
添加到关系名称,您就会得到关联的ID
$categoriesIds = $model->categoriesIds; // [1, 3, 4] // linking $categoriesIds = [2, 3, 5]; $model->categoriesIds = $categoriesIds; $model->save();
添加控制视图以管理相关列表。
不使用扩展,可以使用多选来实现
<?php $categories = ArrayHelper::map(Category::find()->all(), 'id', 'name') ?> <?= $form->field($model, 'categoriesIds')->dropDownList($categories, ['multiple' => true]) ?>
许可证
MIT许可证(MIT)。有关更多信息,请参阅LICENSE.md。