0

Tried to find a solution, but couldn't find a similar problem. I have two classes: Product and TempProduct. Both inherit from BaseProduct. BaseProduct doesn't have a table name defined, but Product and TempProduct do.

I also have an Order model that has the following relation:

public function products()
    {
        return $this->morphTo('products', 'product_type', 'product_id');
    }

The product_type column is an enum with values "product" or "product_temp" to indicate which table the product comes from.

Then I have a Shop model that is connected to Order:

public function shop_order()
    {
        return $this->hasMany(Order::class, 'order_id', 'id')->withTrashed();
    }

Previously, before adding TempProduct, I used the following hasManyThrough relation:

public function products_sell()
    {
        return $this->hasManyThrough(Product::class, Order::class, 'order_id', 'id', 'id', 'product_id');
    }

Now that I've added TempProduct and switched to a polymorphic relation, I'm not sure how to implement hasManyThrough in this case.

1 Answer 1

0

hasManyThrough doesn't work directly with polymorphic relations in Laravel. Since your Order -> Product/TempProduct relationship is now polymorphic (morphTo), you can't simply declare a hasManyThrough anymore.

You could have two explicit relations, then merge.

Define two hasManyThrough relations (one for Product, one for TempProduct) and then merge them when you query:

Something like:

class Shop extends Model
{
    public function orders()
    {
        return $this->hasMany(Order::class);
    }

    public function productsSell()
    {
        return $this->hasManyThrough(
            Product::class,
            Order::class,
            'shop_id',      // Foreign key on Order table
            'id',           // Foreign key on Product table
            'id',           // Local key on Shop table
            'product_id'    // Local key on Order table
        )->where('orders.product_type', '=', Product::class);
    }

    public function tempProductsSell()
    {
        return $this->hasManyThrough(
            TempProduct::class,
            Order::class,
            'shop_id',
            'id',
            'id',
            'product_id'
        )->where('orders.product_type', '=', TempProduct::class);
    }

    public function allProductsSell()
    {
        return $this->productsSell->merge($this->tempProductsSell);
    }
}

Usage:

$shop->allProductsSell();

This gives you two relations you can eager load separately, or a merged collection for "all products".

Hope this helps.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.