mardi 1 octobre 2019

What kind of relationship should I use to relate a model to itself one to one?

I have a product_product pivot table where products can be related from many to many, but in turn I also have another relationship which a product can only have one parent. A composite product can have many common products, and a common product can have many compound parents. A variant product can have many common products, and a common product can have only one variant parent. What are the relationships that I should have?

I am working with laravel 5.7 and php 7.2, I have a products table with an id and a product_product pivot table with an id, product_id (son) and parent_product_id (father)

class Product {
    public function variantParent()
    {
        return $this->hasOne(ProductProduct::class, 'product_id')->where('qty', '=', 0);
    }

    public function variantsChildren()
    {
        return $this->belongsToMany(self::class, 'product_product', 'parent_product_id', 'product_id')
            ->withPivot('qty')->where('qty', '=', 0);
    }

    public function compoundParents()
    {
        return $this->belongsToMany(self::class, 'product_product', 'product_id', 'parent_product_id')
            ->withPivot('qty');
    }

    public function compoundChildren()
    {
        return $this->belongsToMany(self::class, 'product_product', 'parent_product_id', 'product_id')
            ->withPivot('qty');
    }
}

At this moment the variantParent relationship returns me an instance of the ProductProduct pivot table. The variantsChildren relationship returns a collection of Products (this is fine). I need the variantParent relationship to return a Product instance and not a collection.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire