php - 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)?
解决方案
你只需要做
@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
推荐阅读
- delphi - 复制流数据时不断出现读取错误
- angular - switchMap 使用角度 http 客户端保留/取消请求
- firebase-realtime-database - Kotlin 在 Firebase 的类对象警告中找不到值的设置器/字段
- swiftui - SwiftUI 关闭从 NavigationView 呈现的模式表(Xcode Beta 5)
- php - PHP/mysqli:跨两个 mysql 数据库的查询意外回滚
- entity-framework - 在 webapi 中调用 crud 方法的实体框架层需要引用数据层中的实体
- python - 如何在 django 中显示每个用户的特定付款?
- macos-catalina - SIP 被禁用,但 /usr/bin 仍然被写保护(macOS Catalina beta 10.5)
- php - Nginx + php-fpm 502 bad gateway 仅在域上
- android - 我可以使用 admob 插页式广告代替奖励广告吗?