Eloquent - 如何使用 "Has Many Through" 关系?
Eloquent - How to use "Has Many Through" relation?
我有三个表 - 产品、功能和 product_feature - as
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
}
这是一个BelongsToMany
关系:
public function features() {
return $this->belongsToMany(Feature::class, 'product_feature')->withPivot('value');
}
foreach($product->features as $feature) {
// $feature->key
// $feature->pivot->value
}
我有三个表 - 产品、功能和 product_feature - as
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
}
这是一个BelongsToMany
关系:
public function features() {
return $this->belongsToMany(Feature::class, 'product_feature')->withPivot('value');
}
foreach($product->features as $feature) {
// $feature->key
// $feature->pivot->value
}