nyx-solutions/yii2-nyx-ar-many-to-many-link

为Yii2 ActiveRecord提供多对多关系保存支持

5.0.0 2022-06-03 13:55 UTC

This package is not auto-updated.

Last update: 2024-09-21 23:15:38 UTC


README

此扩展为ActiveRecord多对多关系保存提供支持。例如:单个“项目”可以属于多个“组”,每个组可以与多个项目关联。与常规[[\yii\db\BaseActiveRecord::link()]]使用不同,此扩展自动检查引用的存在性,删除排除的引用,并提供对网络表单组成的支持。

有关许可证信息,请检查LICENSE文件。

Latest Stable Version Total Downloads Latest Unstable Version License Monthly Downloads Daily Downloads composer.lock

安装

安装此扩展的首选方式是通过composer

运行以下命令

php composer.phar require --prefer-dist nyx-solutions/yii2-nyx-ar-many-to-many-link

或者

"nyx-solutions/yii2-nyx-ar-many-to-many-link": "*"

将其添加到您的composer.json文件的要求部分。

使用方法

此扩展为ActiveRecord多对多关系保存提供支持。此支持通过[[\nyx\db\LinkManyToManyBehavior]] ActiveRecord行为提供。您需要将其附加到您的ActiveRecord类中,并指定其目标“多对一”关系

class Item extends ActiveRecord
{
    public function behaviors()
    {
        return [
            'linkGroupBehavior' => [
                'class' => LinkManyToManyBehavior::className(),
                'relation' => 'groups', // relation, which will be handled
                'relationReferenceAttribute' => 'groupIds', // virtual attribute, which is used for related records specification
            ],
        ];
    }

    public static function tableName()
    {
        return 'Item';
    }

    public function getGroups()
    {
        return $this->hasMany(Group::className(), ['id' => 'groupId'])->viaTable('ItemGroup', ['itemId' => 'id']);
    }
}

附加[[\nyx\db\LinkManyToManyBehavior]]会给拥有ActiveRecord添加一个虚拟属性,其名称由[[\nyx\db\LinkManyToManyBehavior::$relationReferenceAttribute]]确定。您可以通过此属性指定相关模型的主键

// Pick up related model primary keys:
$groupIds = Group::find()
    ->select('id')
    ->where(['isActive' => true])
    ->column();

$item = new Item();
$item->groupIds = $groupIds; // setup related models references
$item->save(); // after main model is saved referred related models are linked

上述示例等价于以下代码

$groups = Group::find()
    ->where(['isActive' => true])
    ->all();

$item = new Item();
$item->save();

foreach ($groups as $group) {
    $item->link('groups', $group);
}

注意:不要在拥有ActiveRecord类中声明relationReferenceAttribute属性。确保它不会与任何现有拥有字段或虚拟属性冲突。

通过relationReferenceAttribute声明的虚拟属性不仅用于保存。它还包含关系的现有引用

$item = Item::findOne(15);
var_dump($item->groupIds); // outputs something like: array(2, 5, 11)

您还可以在保存链接记录时编辑现有记录的引用列表

$item = Item::findOne(15);
$item->groupIds = array_merge($item->groupIds, [17, 21]);
$item->save(); // groups "17" and "21" will be added

$item->groupIds = [5];
$item->save(); // all groups except "5" will be removed

注意:如果通过relationReferenceAttribute声明的属性从未被调用过读取或写入,它将不会在拥有保存时进行处理。因此,它不会影响纯拥有保存。

创建关系设置Web界面

[[\nyx\db\LinkManyToManyBehavior::$relationReferenceAttribute]]的主要目的是支持创建多对多设置Web界面。您需要做的是在ActiveRecord中声明一个对此虚拟属性的验证规则,以便可以从请求中收集其值

class Item extends ActiveRecord
{
    public function rules()
    {
        return [
            ['groupIds', 'safe'] // ensure 'groupIds' value can be collected on `populate()`
            // ...
        ];
    }

    // ...
}

在视图文件中,您应使用relationReferenceAttribute属性作为表单输入的属性名

<?php
use yii\helpers\ArrayHelper;
use yii\helpers\Html;
use yii\widgets\ActiveForm;

/* @var $model Item */
?>
<?php $form = ActiveForm::begin(); ?>

<?= $form->field($model, 'name'); ?>
<?= $form->field($model, 'price'); ?>

<?= $form->field($model, 'groupIds')->checkboxList(ArrayHelper::map(Group::find()->all(), 'id', 'name')); ?>

<div class="form-group">
    <?= Html::submitButton('Save', ['class' => 'btn btn-primary']) ?>
</div>

<?php ActiveForm::end(); ?>

在控制器中,您不需要任何特殊代码

use yii\web\Controller;

class ItemController extends Controller
{
    public function actionCreate()
    {
        $model = new Item();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view']);
        }

        return $this->render('create', ['model' => $model]);
    }

    // ...
}

详细信息

此扩展基于Paul Klimov提供的扩展(但未维护)https://github.com/yii2tech/ar-linkmany