雄辩的-如何使用“有很多通过”关系?

时间:2018-09-05 03:23:52

标签: eloquent has-many-through laravel-5.6 eloquent--relationship

我有三个表-产品,功能和product_feature-

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

我检索了产品的所有(键,值)对。 SQL语句是

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

我如何建立这种关系

// Inside Product model
function features() {
    // Has many through relationship
}

1 个答案:

答案 0 :(得分:0)

这是BelongsToMany关系:

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

foreach($product->features as $feature) {
    // $feature->key
    // $feature->pivot->value
}