首页 > 解决方案 > 背包换laravel select2_multiple 字段具有相同的数据透视表但同一表单上的不同字段

问题描述

我正在制作这个项目,其中我有两个(或更多)具有相同数据透视表的字段,并且正在使用背包换 laravel 上的关系类型。我想做的是让这两个领域独立工作。

因此,假设我想要一个用户选择厚度的字段,而在另一个字段中用户可以选择阴影。

问题是这两个字段具有相同的数据透视表和模型中设置的相同关系,因此它们中只有一个会以相同的形式显示。我确实知道 HTML 表单用相同的“名称”属性替换了字段,但我想知道如何解决这个问题并让这些字段独立工作以维护 select2_multiple 功能。

表结构(Collection 与 Collection Attributes 有 nn 关系)

Collection:
 id
 collection_name
 .....

CollectionAttributes:
 id
 attribute_name
 attribute_value
 ...

CollectionAttrValues
 fk_col_id
 fk_attr_val_id

模型关系法:

public function collectionAttributeValues()
    {
        return $this->belongsToMany('App\Models\AttributeValue', 'collections_attr', 'fk_collection_id', 'fk_attr_val_id');
    }

控制器字段代码:

CRUD::addField([   // relationship
            'type' => "relationship",
            'name' => 'collectionAttributeValues', // the method on your model that defines the relationship
        
            // OPTIONALS:
            'label' => "Thickness",
            'attribute' => "attr_val", // foreign key attribute that is shown to user (identifiable attribute)
            'entity' => 'collectionAttributeValues', // the method that defines the relationship in your Model
            'model' => "App\Models\AttributeValue", // foreign key Eloquent model
            // 'placeholder' => "Select a category", // placeholder for the select2 input
            'options'   => (function ($query) {
                $thickness_id = \App\Models\Attribute::select('attr_id')
                ->where('fk_attr_category', 1)
                ->where('attr_type', 'collection')
                ->where('attr_name', 'Thickness')->get()->first()->attr_id;

                return $query->orderBy('attr_val', 'desc')->where('fk_attr_id', $thickness_id)->get();
            }),
         ]);

         CRUD::addField([   // relationship
            'type' => "relationship",
            'name' => 'collectionAttributeValues', // the method on your model that defines the relationship
        
            // OPTIONALS:
            'label' => "Shading",
            'attribute' => "attr_val", // foreign key attribute that is shown to user (identifiable attribute)
            'entity' => 'collectionAttributeValues', // the method that defines the relationship in your Model
            'model' => "App\Models\AttributeValue", // foreign key Eloquent model
            // 'placeholder' => "Select a category", // placeholder for the select2 input
            'options'   => (function ($query) {
                $shading = \App\Models\Attribute::select('attr_id')
                ->where('fk_attr_category', 1)
                ->where('attr_type', 'collection')
                ->where('attr_name', 'Shading')->get()->first()->attr_id;

                return $query->orderBy('attr_val', 'desc')->where('fk_attr_id', $shading)->get();
            }),
         ]);

标签: phplaravellaravel-backpack

解决方案


推荐阅读