繁体   English   中英

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

[英]How do I access third table via Many-to-Many Relation in Laravel?

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

有任何想法吗? 建议?

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

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

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

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

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

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

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

产品型号:

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

AttributeValue模型:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM