greyworm's avatar

N+1 Error on Two Foreign Keys From The Same Model

Hello everyone! I hope all is well.

On my laravel app, I have installed beyondcode/laravel-query-detector to catch N+1 queries.

I have two models, Unit and Product.

On my Product model, i have two relationships referencing to Unit model:

// Product model
public function sale_unit(): BelongsTo
{
    return $this->belongsTo(Unit::class, 'sale_unit_id');
}

public function purchase_unit(): BelongsTo
{
    return $this->belongsTo(Unit::class, 'purchase_unit_id');
}

On my ProductController, I have eager loaded the relationships:

// ProductController
public function index(): View|Application|Factory
{
    $products = Product::with(
        [
            'sale_unit',
            'purchase_unit',
        ]
    )->get();

    return view('products', compact('products'));
}

And on my blade file, I displayed the $product->sale_unit->name and $product->purchase_unit->name, but every time I access the product's list, I get "Found the following N+1 queries in this request:".

Is there something wrong or missing on my code? Please help. Thank you.

0 likes
2 replies
greyworm's avatar

By the way, this is the migration file of Product model.

Schema::create('products', function (Blueprint $table) {
    $table->id();
    $table->string('name');
    $table->bigInteger('sale_unit_id')
        ->references('id')
        ->on('units')
        ->index();
    $table->bigInteger('purchase_unit_id')
        ->references('id')
        ->on('units')
        ->index();
    $table->timestamps();
});
greyworm's avatar

These are my sample data:

// Unit
id | name 
1  | pc.

// Product
id | name      | sale_unit_id | purchase_unit_id
1  | Product 1 | 1            | 1
2  | Product 2 | 1            | 1

Please or to participate in this conversation.