【发布时间】:2017-06-25 04:07:57
【问题描述】:
我正在使用 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 以及属性名称吗?换句话说,我如何访问属性表以及属性值?将使用哪种关系?
有什么想法吗?建议?
【问题讨论】:
-
@Thomas 你能发一个示例代码吗?
-
我现在不能,因为要准确理解您当前的问题需要太多时间。你能把问题简化成你期望的输出吗?
-
@Thomas 我想使用属性名称和值对访问产品属性。即:网络:3G。
-
@GopaThemes 您提供的表格描述不太清楚。一个是,
attributes上的产品可能没有参考,id或者您是否以任何方式错过了它?
标签: php mysql laravel database-design laravel-5.4