【问题标题】:Laravel 5 multi-level relations with pivot tableLaravel 5 与数据透视表的多级关系
【发布时间】:2018-07-15 19:01:55
【问题描述】:

我正在为 Laravel 5 数据透视表或多级关系而苦苦挣扎,我想出了如何获得所需的结果,但我认为我这样做的方式是错误的,因为我应该循环两次几乎相同得到预期结果的数据。此外,所有属性和选项都是可翻译的。

获取结果(可翻译的属性和选项)

$product = App\Model\Product::find(1);

foreach ($product->attributeData as $key => $value) {
    foreach ($value->attributes as $k => $v) {
        echo $v->{'name:en'}.' '.$v->currentOption->{'option_name:en'}.'<br>';
    }
}

有 3 个表(product_attributes、attributes、options)

-- product_attributes [ id|product_id|attribute_id|option_id ]
-- attributes [ id ] ( name, etc. on translation table )
-- attribute_options [ id|attribute_id ] ( name and other data also in stranslation table )

产品型号

public function attributeData() : HasMany
{
    return $this->hasMany(ProductAttribute::class);
}

产品属性模型

public function product()
{
    return $this->belongsTo(Product::class);
}

public function attributes()
{
    return $this->hasMany(Attribute::class,'id','attribute_id');
}

public function options()
{
    return $this->hasMany(AttributeOption::class,'id','option_id');
}

属性模型

public function options() : HasMany
{
    return $this->hasMany('App\Model\AttributeOption', 'attribute_id', 'id');
}

public function product()
{
    return $this->belongsTo(ProductAttribute::class,'id','attribute_id');
}

public function currentOption()
{
    return $this->hasOne(AttributeOption::class)->whereId($this->product()->first()->option_id);
}

属性选项模型

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

我做错了什么,有没有可能避免这种多循环?

【问题讨论】:

    标签: php laravel laravel-5 eloquent relationship


    【解决方案1】:

    ProductAttribute 之间的关系是BelongsToMany

    public function attributes()
    {
        return $this->belongsToMany(Attribute::class, 'product_attributes');
    }
    
    foreach ($product->attributes as $attribute) {
    
    }
    

    【讨论】:

      猜你喜欢
      • 2018-09-23
      • 1970-01-01
      • 2017-07-22
      • 2014-08-26
      • 1970-01-01
      • 2016-03-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多