如何通过拉拉维尔中的多对多关系访问第三个表



我正在使用Laravel5.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('AppAttributeValue', 'attribute_product');
    }
}

属性.php

class Attribute extends Model
{
    public function products() {
        return $this->belongsToMany('AppProduct');
    }

    public function values() {
        return $this->hasMany(AttributeValue::class);
    }
}

属性值.php

class AttributeValue extends Model
{
    public $timestamps = false;
    public function attribute() {
        return $this->belongsTo( AppAttribute::class );
    }
}

我可以使用以下代码访问产品属性值:

$p = AppProduct::find(1);
$p->attributeValues;

通过此代码,我能够检索产品属性值。但是我可以访问attributeValues以及属性名称吗?换句话说,如何访问属性表以及属性值?将使用哪种关系?

有什么想法吗?建议?

我曾经用load方法做过这样的事情,即

$p = AppProduct::find(1);
$p->load('attributeValues.attribute');

所以对于每个属性,获取相应的属性它也应该适合你...

PS:我不能打赌这是最好的方法。但是我已经在Laravel 5.2项目中使用了这种技术

你用错了地方,使用你用来描述模型中关系的相同名称。

$product = AppProduct::with('attributeValues.attribute')->find(1)

如果 Product belonsToMany AttributeValue,AttributeValue 应该属于 ToMany Product。

产品型号:

public function attributeValues() {
        return $this->belongsToMany('AppAttributeValue', 'attribute_product');
    }

属性值模型:

public function products() {
        return $this->belongsToMany('AppProduct');
    }
public function attribute() {
    return $this->belongsTo( AppAttribute::class );
}

属性模型:

  public function values() {
        return $this->hasMany(AttributeValue::class);
    }

$product = AppProduct::find(1);
foreach($product->attributeValues as $attributeValue)
{
   echo $attributeValue;
   echo $attributeValue->attribute;
}

最新更新