Download the PHP package ajcastro/eager-load-pivot-relations without Composer
On this page you can find all versions of the php package ajcastro/eager-load-pivot-relations. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download ajcastro/eager-load-pivot-relations
More information about ajcastro/eager-load-pivot-relations
Files in ajcastro/eager-load-pivot-relations
Package eager-load-pivot-relations
Short Description Eager load pivot relations for Laravel Eloquent's BelongsToMany relation.
License MIT
Informations about the package eager-load-pivot-relations
Laravel Eloquent: Eager Load Pivot Relations
Eager load pivot relations for Laravel Eloquent's BelongsToMany relation.
Medium Story: https://medium.com/@ajcastro29/laravel-eloquent-eager-load-pivot-relations-dba579f3fd3a
Installation
Usage and Example
There are use-cases where in a pivot model has relations to be eager loaded. Example, in a procurement system, we have the following:
Tables
Models
From the code above, plans
and items
has Many-to-Many
relationship. Each item in a plan has a selected unit
, unit of measurement.
It also possible for other scenario that the pivot model will have other many relations.
Eager Loading Pivot Relations
Use keyword pivot
in eager loading pivot models. So from the example above, the pivot model PlanItem
can eager load the unit
relation by doing this:
The resulting data structure will be:
You may also access other relations for example:
Custom Pivot Accessor
You can customize the "pivot accessor", so instead of using the keyword pivot
, we can declare it as planItem
.
Just chain the as()
method in the definition of the BelongsToMany
relation.
Make sure we also use the trait
to our main model which is the Plan
model, because the package needs to acess
the belongsToMany relation (items
relation) to recognize the used pivot acessor.
So instead of using pivot
, we can eager load it by defined pivot accessor planItem
.
Other Examples and Use-cases
https://github.com/ajcastro/eager-load-pivot-relations-examples