ajcastro / eager-load-pivot-relations

Eager load pivot relations for Laravel Eloquent's BelongsToMany relation.
https://medium.com/@ajcastro29/laravel-eloquent-eager-load-pivot-relations-dba579f3fd3a
238 stars 22 forks source link

Eager Loading not Working for BelongsToMany Pivot Relation #15

Open nouman-ashraf-awan opened 4 days ago

nouman-ashraf-awan commented 4 days ago

Laravel Version: 9.0 Nova Version: 3.0 PHP Version: 8.1 Description: BelongsToMany relationships with custom pivot fields are not eager loading nested relation in the Nova resource.

Detailed steps to reproduce the issue on a fresh Nova installation: Create a Group model with a currencies relation:

public function currencies(): BelongsToMany { return $this->belongsToMany( Currency::class, CurrencyGroup::class, 'group_id', 'currency_id' ) ->withPivot('id', 'amount', 'remaining', 'type', 'begins_at', 'expires_at', 'contract_id') ->withTimestamps(); } In Nova Resource BelongsToMany::make('Currencies Breakdown', 'currencies', Currency::class) ->fields(new CurrencyGroupFields) ->allowDuplicateRelations() ->canSee(fn () => Setting::get('ff_enable_currency_system')),

In CurrencyGroup Model public function currencyUsers() { return $this->hasMany(CurrencyUser::class, 'currency_group_id', 'id'); }

Now wants to eager load currencies.pivot.currencyUsers or some other relations in Group Resource but not working. Creating N+1 Problem. While using detailQuery method, eager loading working for nova-api/groups/ID but not in /nova-api/currencies?orderBy=&page=1&perPage=5&relationshipType=belongsToMany&search=&trashed=&viaRelationship=currencies&viaResource=groups&viaResourceId=ID

Tried this package https://github.com/ajcastro/eager-load-pivot-relations too but not working in Nova. Its working in Model but not in Nova.

nouman-ashraf-awan commented 4 days ago

@ajcastro