我正在使用 Laravel 5.4 开发一个电子商务网站。这是数据库结构:
Products Table:
ID - Product Name
1 - Test Mobile
Attributes Table
ID - AttributeName
1 - Network
AttributeValues Table
ID - AttributeID - AttributeValue
1 - 1 - 2G
2 - 1 - 3G
3 - 1 - 4G
ProductAttributes Table
ID - AttributeValueID - ProductID
1 - 2 - 1
2 - 3 - 1
以下是关系:
产品.php
class Product extends Model
{
public function attributeValues() {
return $this->belongsToMany('App\AttributeValue', 'attribute_product');
}
}
属性.php
class Attribute extends Model
{
public function products() {
return $this->belongsToMany('App\Product');
}
public function values() {
return $this->hasMany(AttributeValue::class);
}
}
属性值.php
class AttributeValue extends Model
{
public $timestamps = false;
public function attribute() {
return $this->belongsTo( App\Attribute::class );
}
}
我可以使用以下代码访问产品属性值:
$p = App\Product::find(1);
$p->attributeValues;
通过此代码,我能够检索产品属性值。但是我可以访问attributeValues
属性名称吗?换句话说,我如何访问属性表以及属性值?将使用哪种关系?
有任何想法吗?建议?