首页 > 解决方案 > laravel 嵌套关系数据透视表

问题描述

这是我的数据库表,每个产品可以有多个属性,每个属性都有多个值,可以在产品编辑页面的选择框中选择。

属性表:

+-----------------------+
|       attributes      |
+====+======+===========+
| id | name | type      |
+----+------+-----------+
| 1  | size | selectbox |
+----+------+-----------+
| 2  | ...  | ....      |
+----+------+-----------+

属性值表:

+-----------------------------+
|       attribute_values      |
+====+==============+=========+
| id | attribute_id | value   |
+----+--------------+---------+
| 1  | 1            | sample1 |
+----+--------------+---------+
| 2  | 1            | sample2 |
+----+--------------+---------+
| 3  | 1            | sample3 |
+----+--------------+---------+

产品表:

+----------------+
|    products    |
+====+===========+
| id | name      |
+----+-----------+
| 1  | product 1 |
+----+-----------+
| 2  | product 2 |
+----+-----------+

属性产品表:

+-------------------------------------------+
|             attribute_product             |
+====+============+==============+==========+
| id | product_id | attribute_id | value_id |
+----+------------+--------------+----------+
| 1  | 1          | 1            | 1        |
+----+------------+--------------+----------+
| 2  | 1          | 1            | 2        |
+----+------------+--------------+----------+

关系

class Attribute extends Model
{
    public function products()
    {
        return $this->belongsToMany(Product::class);
    }
}



class AttributeValue extends Model
{

}


class Product extends Model
{
    public function attributes()
    {
        return $this->belongsToMany(Attribute::class, 'attribute_product')
            ->withPivot('value_id');
    }
}

刀:

@foreach($product->attributes as $attribute)
    Attribute Name: {{ $attribute->name }}
    <select>
        @foreach($attribute->values as $value)
            <option id="{{ $value->id }}">{{ $value->id }}</option>
        @endforeach
    </select>
@endforeach

如何添加“已选择”以选择框选择选项(attribute_product 中的 value_id)?

标签: phplaravelrelationship

解决方案


你只需要做

@foreach($product->attributes as $attribute)
    Attribute Name: {{ $attribute->name }}
    <select>
        @foreach($attribute->values as $value)
            <option id="{{ $value->id }}" {{ $attribute->pivot->value_id == $value->id ? 'selected' :  '' }} >{{ $value->id }}</option>
        @endforeach
    </select>
@endforeach

推荐阅读