【发布时间】:2021-08-21 10:13:08
【问题描述】:
大家好,我必须通过另一个表创建多对多关系。但是 laravel BelongsToMany 只给出 1 个中间表关系
这里的表结构:
features Table:
+----+-----------+
| id | text |
+----+-----------+
| 1 | feature 1 |
+----+-----------+
| 2 | feature 2 |
+----+-----------+
feature_values table:
+----+-----------+-------+
| id | feature_id | text |
+----+-----------+-------+
| 1 | 1 | val 1 |
+----+-----------+-------+
| 2 | 1 | val 2 |
+----+-----------+-------+
| 3 | 2 | val 3 |
+----+-----------+-------+
products table:
+----+-------+
| id | name |
+----+-------+
| 1 | tv |
+----+-------+
| 2 | phone |
+----+-------+
product_features table:
+----+------------+------------+
| id | product_id | feature_id |
+----+------------+------------+
| 1 | 1 | 1 |
+----+------------+------------+
| 2 | 2 | 1 |
+----+------------+------------+
| 3 | 2 | 2 |
+----+------------+------------+
product_feature_values table:
+----+--------------------+------------------+
| id | product_feature_id | feature_value_id |
+----+--------------------+------------------+
| 1 | 1 | 1 |
+----+--------------------+------------------+
| 2 | 2 | 1 |
+----+--------------------+------------------+
| 3 | 2 | 2 |
+----+--------------------+------------------+
我正在尝试通过product_feature_values 和product_features 在feature_values 和products 之间建立关系,以便通过feature_values 获取product。
我知道数据可以通过加入表格获得,但我正在寻找一个通过 laravel 模型关系使用的解决方案
谢谢。
我试过这样
class FeatureValue extends Model
{
public function products()
{
return $this->belongsToMany(Product::class,'product_feature_values')->withTimestamps();
}
}
【问题讨论】:
标签: php laravel eloquent-relationship