this is my database tables that each product can have multiple attributes and each attribute has multiple values that can be selected in the Select Box on the product edit page.
attribute 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 |
+----+--------------+---------+
products 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 |
+----+------------+--------------+----------+
relationships
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
how to add 'selected' to select box selected options (value_id in attribute_product)?
question from:
https://stackoverflow.com/questions/66053100/laravel-nested-relationships-pivot-table 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…