Reputation: 520
Hi guys I have to create many to many relationship but through a another table. but laravel BelongsToMany
give only 1 intermediate table relation
here table structure:
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 |
+----+--------------------+------------------+
I'm trying to create a relationship between feature_values
and and products
through product_feature_values
and product_features
for get product
by feature_values
.
I know data can obtain by joining tables, but I looking for a solution that using by laravel model relationships
thank you.
I tried like this
class FeatureValue extends Model
{
public function products()
{
return $this->belongsToMany(Product::class,'product_feature_values')->withTimestamps();
}
}
Upvotes: 1
Views: 774
Reputation: 5735
I'm afraid, that Laravel didn't offer that out-of the box. But there's a package called staudenmeir/belongs-to-through
that does.
Upvotes: 2