laravel 嵌套关系枢轴 table

laravel nested relationships pivot table

这是我的数据库 table,每个产品可以有多个属性,每个属性有多个值,可以在产品编辑页面的 Select 框中 selected .

属性table:

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

attribute_values table:

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

产品table:

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

attribute_product table:

+-------------------------------------------+
|             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');
    }
}

blade:

@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

如何将 'selected' 添加到 select 框 selected 选项(value_id in attribute_product)?

你只需要做

@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