Skip to content

BelongsToMany runs excessive (heavy) queries #6451

@fruitl00p

Description

@fruitl00p
  • Laravel Version: 11.10
  • Nova Version: 4.34.3
  • PHP Version: 8.3
  • Database Driver & Version: MariaDB 11.2.3

Description:

We have a BelongsToMany relation which seems to do a lot of queries eventhough the original pivot is empty?

We have the following setup:

Model: Compontent

    public function cook_products(): BelongsToMany
    {
        return $this->belongsToMany(Product::class)
            ->wherePivot('direction', ComponentProductDirection::ToProduct)
            ->withPivot(['direction', 'quantity']);
    }

And in Nova we have:

            BelongsToMany::make(__('Cook products'), 'cook_products', Product::class)
                ->searchable()
                ->fields(fn () => [
                    Number::make(__('Quantity'), 'quantity')
                        ->readonly(!$request->user()->isAdmin())
                        ->rules('required'),
                    Hidden::make('direction')
                        ->default(ComponentProductDirection::ToProduct),
                ]),

When hitting the details page this incurs a /nova-api/products?search request with the following filter (shortened):

[
  "search" => ""
  "filters" => "<some hash, removed for brevity>"
  "orderBy" => ""
  "perPage" => "5"
  "trashed" => ""
  "page" => "1"
  "viaResource" => "components"
  "viaResourceId" => "25"
  "viaRelationship" => "cook_products"
  "relationshipType" => "belongsToMany"
]

This results in 14 queries of which 10 are duplicate?

image

(even though there were no relations)

If having 9 actual cook_products relations this balloons to 67 queries of which 7 where unique (!)

I'm not sure if this is a bug, a feature request or missing documentation. (or something else)

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions