dimanche 15 juillet 2018

Laravel 5 multi-level relations with pivot table

I'm struggling with Laravel 5 pivot tables or multi-level relations, I figured out how to get the result I needed, but I think that the way I'm doing it is wrong, cause I should loop twice almost same data to get the expected result. Also all attributes and options are translatable.

Getting the results ( translatable attribute and option )

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

There are 3 tables ( 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 )

Product model

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

Product Attribute model

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

Attribute model

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

Attribute Option model

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

What I'm doing wrong, and is there any possibility to avoid this multi-looping?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire