如何通过Laravel中的多对多关系访问第三个表?

时间:2017-02-07 19:05:08

标签: php mysql laravel database-design laravel-5.4

我正在使用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

以下是关系:

Product.php

class Product extends Model
{

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

}

Attribute.php

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


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

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

有什么想法吗?建议?

3 个答案:

答案 0 :(得分:0)

我曾用load方法做过类似的事情,即

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

因此,对于每个 attributeValue ,请获取相应的属性 它也适合你......

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

答案 1 :(得分:0)

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

$product = App\Product::with('attributeValues.attribute')->find(1)

答案 2 :(得分:0)

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

产品型号:

float(money) += float(line)

AttributeValue模型:

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);
    }