1

我正在使用 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属性名称吗?换句话说,我如何访问属性表以及属性值?将使用哪种关系?

有任何想法吗?建议?

4

3 回答 3

0

您在错误的地方使用它,请使用您用于描述模型中关系的相同名称。

$product = App\Product::with('attributeValues.attribute')->find(1)
于 2017-02-07T22:54:01.413 回答
0

如果 Product 属于ToMany AttributeValue,AttributeValue 应该属于ToMany 产品。

产品型号:

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

属性值模型:

public function products() {
        return $this->belongsToMany('App\Product');
    }

public function attribute() {
    return $this->belongsTo( App\Attribute::class );
}

属性模型:

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

和,

$product = App\Product::find(1);
foreach($product->attributeValues as $attributeValue)
{
   echo $attributeValue;
   echo $attributeValue->attribute;
}
于 2017-02-08T03:25:20.037 回答
0

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

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

所以对于每个attributeValue,获取相应的属性 它也应该对你有用......

PS:我不敢打赌这是最好的方法。但我已将这种技术用于 Laravel 5.2 项目

于 2017-02-07T19:13:01.003 回答