0

I have three tables - products, features and product_feature - as

products
    - id
    - name
features
    - id
    - key
product_feature
    - product_id
    - feature_id
    - value

I was retrieve all (key, value) pairs for a product. The SQL statement is

SELECT key, value FROM products
JOIN product_feature pf
ON pf.product_id = "Product ID"
JOIN features f
ON f.id = pf.feature_id

How do I established that relationship

// Inside Product model
function features() {
    // Has many through relationship
}
Tushar Bhatt
  • 15
  • 1
  • 11

1 Answers1

0

This is a BelongsToMany relationship:

public function features() {
    return $this->belongsToMany(Feature::class, 'product_feature')->withPivot('value');
}

foreach($product->features as $feature) {
    // $feature->key
    // $feature->pivot->value
}
Jonas Staudenmeir
  • 24,815
  • 6
  • 63
  • 109