laravel reverse polymorph issue

626 views Asked by At

In laravel i have tables cart, cart_products, tests, packages. - what i need to relate these tables using laravel ORM. In cart_products table, sometime it will have test, sometime it will have package. so how should i related them ? In Cart model relate like

public function products(){
        return $this->hasMany('HbDiagnostic\Models\CartProduct');
    }

and getting data like..

"products": [
        {
            "id": "1",
            "cart_id": "1",
            "productable_id": "2",
            "productable_type": "test",
            "quantity": "1",
            "created_at": "2015-06-10 07:23:59",
            "updated_at": "2015-06-10 07:23:59"
        },
        {
            "id": "2",
            "cart_id": "1",
            "productable_id": "1",
            "productable_type": "package",
            "quantity": "1",
            "created_at": "2015-06-10 07:23:59",
            "updated_at": "2015-06-10 07:23:59"
        }];

Now i also need Test details and Package details as well with each product. Please help me, i have tried few way but did not get it right.

Thanks, sanjit

2

There are 2 answers

0
Chanom First On

I'm Beginner for Laravel too but I understood about Eloquent Like this

1:N = hasMany

N:1 = BelongTo

N:N = BelongToMany

So you have 4 Tables Cart,cart_product, test,package

If i understand these table it should 4 Base table and 1 Composite table (Cart_product)

Cart,product,test,package,and Cart_Product (Composite Table)

about relation see this link below

http://daylerees.com/codebright/eloquent-relationships

http://laravel.com/docs/4.2/eloquent

0
Sanjit Bauli On

@Chanom, Thanks for your answer, but my query was related to tag tests and package with cart_product table and finally it works for me... relations are like :

Model CartProduct:
public function productable(){
        return $this->morphTo();
    }

Model Test :
public function cart_product(){
        return $this->morphMany('HbDiagnostic\Models\CartProduct', 'productable');

Model Package :
    public function cart_product(){
            return $this->morphMany('HbDiagnostic\Models\CartProduct', 'productable');

And finally i am retrieving results like 
$cartProduct=CartProduct::Query()->where('cart_id',$cart->id);
            return $cartProduct->with('productable')->get();
    }

These links helped me a lot.. Laravel - Eager Loading Polymorphic Relation's Related Models and Laravel: Returning the namespaced owner of a polymorphic relation