skip to Main Content

my product has relation called values which is like this:

public function values()
{
    return $this->hasManyThrough(VariantValue::class, VariantProductOption::class, 'product_id', 'product_option_id');
}

everything works fine but when i have a multiple products in a single pages n+1 problem happens:

select `variant_sku_values`.*, `variant_sku_product_options`.`product_id` as `laravel_through_key` from `variant_sku_values` inner join `variant_sku_product_options` on `variant_sku_product_options`.`id` = `variant_sku_values`.`product_option_id` where `variant_sku_product_options`.`product_id` = 61520 and `option_id` = 1
1.16ms
-----------------------------------------
arya-lion
select `variant_sku_values`.*, `variant_sku_product_options`.`product_id` as `laravel_through_key` from `variant_sku_values` inner join `variant_sku_product_options` on `variant_sku_product_options`.`id` = `variant_sku_values`.`product_option_id` where `variant_sku_product_options`.`product_id` = 81066 and `option_id` = 1
1.09ms
-----------------------------------------
arya-lion
select `variant_sku_values`.*, `variant_sku_product_options`.`product_id` as `laravel_through_key` from `variant_sku_values` inner join `variant_sku_product_options` on `variant_sku_product_options`.`id` = `variant_sku_values`.`product_option_id` where `variant_sku_product_options`.`product_id` = 81069 and `option_id` = 1
1.07ms
------------------------------------------
arya-lion
select `variant_sku_values`.*, `variant_sku_product_options`.`product_id` as `laravel_through_key` from `variant_sku_values` inner join `variant_sku_product_options` on `variant_sku_product_options`.`id` = `variant_sku_values`.`product_option_id` where `variant_sku_product_options`.`product_id` = 93662 and `option_id` = 1
1ms
-----------------------------------------
arya-lion
select `variant_sku_values`.*, `variant_sku_product_options`.`product_id` as `laravel_through_key` from `variant_sku_values` inner join `variant_sku_product_options` on `variant_sku_product_options`.`id` = `variant_sku_values`.`product_option_id` where `variant_sku_product_options`.`product_id` = 93724 and `option_id` = 1

i tried to eager load the values relation but this doesnt work.

2

Answers


  1. Chosen as BEST ANSWER

    with help of @Coola i somehow find the solution by eagerloading the relation like below:

    Product::query()->with([
                    'values' => ['value' => ['option']],
                ])
    

  2. You can use with for eager loading like this-

    public function values()
    {
        return $this->hasManyThrough(VariantValue::class, VariantProductOption::class, 'product_id', 'product_option_id')
                    ->with('variantProductOption');
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search