What this package was originally intended to do has been much better executed with this alternative package: https://github.com/kirschbaum-development/eloquent-power-joins.
One area that I explore here that is lacking from the aforementioned package is the hydration of related models. However my implementation is far from optimized so I would only use this package as a proof-of-concept.
Eager-load your eloquent relationships in Laravel using joins instead of separate queries.
composer require joeyrush/eager-joins
- Attach the trait to your individual models or base model:
class Post extends Model
{
use \JoeyRush\EagerJoins\JoinRelations;
public function category()
{
return $this->belongsTo(Category::class);
}
}
- Specify which
$fields
should be loaded in the joins on the related model:
class Category extends Model
{
/** @var array */
public $fields = ['id', 'name'];
}
And now you can eager-load using joins by calling the include($relationName)
method on your model/query builder wherever you would previously call the with($relationName)
method.
// The following will return all posts, each with their associated category pre-loaded.
$posts = Post::include('category')->get();
By default, the relationship fields will be stored on the original model, e.g. the following will return Post
models with category_name
and category_id
stored directly on the model.
$posts = Post::include('category')->get();
If you'd like to have the related models hydrated and linked up correctly, you can call populateRelationships()
Note: the larger the data set, the more of a performance penalty this will incur.
$posts = Post::populateRelationships()->include('category')->get();
You can use dot notation to eager-load nested relations. This only works on HasOne and BelongsTo relationships
$posts = Post::include('category.creator.profile')->get();
You can eager load as many relationships as needed
$posts = Post::query()
->include('category.creator.profile')
->include('tags')
->include('author')
->first();
- You cannot limit or paginate your queries when eager-joining
HasMany
/BelongsToMany
relationships due to SQL limitations - You cannot eager-load nested
HasMany
orBelongsToMany
relationships. - You cannot join on multiple relationships with the same table yet.