If you have some experience using databases, it is very likely you have used joins
at least once in your career. Joins can be used for a bunch of different reasons, from selecting data from other tables to limiting the matches of your query.
I'm going to give a few examples on this post, so, in order to contextualize the examples, imagine we have the following database/models structure.
User
-> hasMany
-> Post
Post
-> hasMany
-> Comment
Post
-> morphMany
-> Image
On Laravel, using eloquent, joining the posts
table would look something like this:
1User::select('users.*')->join('posts', 'posts.user_id', '=', 'users.id');
In case you want to join the posts and the comments table, your query would look something like this:
1User::select('users.*')2 ->join('posts', 'posts.user_id', '=', 'users.id')3 ->join('comments', 'comments.post_id', '=', 'posts.id');
This is fine and we can understand, but we can do better. We already have all these relationships defined in our models, but we are repeating some of the implementation details when we write the join statements. So, instead of doing this, wouldn't be cool if you could just do the following?
1// example 12User::joinRelationship('posts');3 4// example 25User::joinRelationship('posts.comments');
This is less code to read, and more importantly, easier code to read. It also hides any implementation details on how your relationships work. So, if your relationship changes, your joins will be automatically updated.
Introducing the Eloquent Power Joins package
We felt the way we did joins in our applications wasn't really the “Laravel way”, so we decided to introduce some of the Laravel fine touch into the way we do joins.
joinRelationship
is a method introduced by the Eloquent Power Joins package. It works with any type of the existing Laravel relationships.
The installation of the package is as simple as just running the following composer command, and you should already have access to everything that will be mentioned on this post.
1composer require kirschbaum-development/eloquent-power-joins
On any model you want to be able to use the methods described below, you should use the following trait:
1use Kirschbaum\PowerJoins\PowerJoins;2 3class User extends Model4{5 use PowerJoins;6}
Joining polymorphic relationships
The joinRelationship
method also works polymorphic relationships. Besides performing the regular join, it also performs the {morph}_type == Model::class
check, as you can see below.
1Post::joinRelationship('images')->toSql();2 3// select * from posts4// inner join images on images.imageable_id = posts.id AND images.imageable_id = 'App\\Post'
Joining nested relationships
And, it also works with nested relationships.
1User::joinRelationship('posts.images')->toSql();2 3// select * from users4// inner join posts on posts.user_id = users.id5// inner join images on images.imageable_id = posts.id AND images.imageable_id = 'App\\Post'
It works with any relationship
The package will work with any of the native relationship types provided from Laravel.
BelongsToMany
will make 2 joins considering the pivot table as well. HasManyThrough
also makes the 2 necessary joins.
Eloquent Power Joins also applies any soft deletes clauses in case the related model uses the SoftDeletes
trait.
But, the package also provides you with a few other very useful features, as you can see below.
Applying extra conditions to the joins
You can apply any extra condition you need to the joins, as well.
1User::joinRelationship('posts', function ($join) {2 $join->where('posts.published', true);3});
For nested calls, and/or BelongsToMany
or HasManyThrough
relationships, you need to pass an array with the relationship as the key.
1User::joinRelationship('posts.images', [2 'posts' => function ($join) {3 $join->where('posts.published', true);4 },5 'images' => function ($join) {6 $join->where('images.cover', true);7 },8]);
Using model scopes inside the callbacks 🤯
We consider this one of the most useful features of this package. Let's say, you have a published
scope on your Post
model:
1public function scopePublished($query)2{3 $query->where('published', true);4}
When joining relationships, you can use the scopes defined in the model being joined. How cool is this?
1User::joinRelationshio('posts', function ($join) {2 // the $join instance here can access any of the scopes defined in the Post model 🤯3 $join->published();4});
Querying relationship existence
Querying relationship existence is a very powerful and convenient feature of Eloquent. However, it uses the where exists
syntax which is not always the best and more performant choice, depending on how many records you have or the structure of your table.
This package also implements almost all Laravel methods for querying relationship existence using joins
instead of where exists
.
Performance
First thing to be aware here, is that the below example is one use-case where using joins over where exists is a lot more performant. You shouldn't assume this is true for every query, and you should use tools like Laravel Debugbar , Laravel Telescope or any tool of your choice to figure out what's best for YOUR use-case.
That said, below you can see one example of the MySQL CPU usage after deploying a change to use powerJoinHas instead of has, in one of our client's application. MySQL was running on RDS, and this image was took from AWS CloudWatch.
Show me the code
Below, you can see the methods this package implements and also the Laravel equivalent.
Laravel Native Methods
1User::has('posts');2User::has('posts.comments');3User::has('posts', '>', 3);4User::whereHas('posts', function ($query) {5 $query->where('posts.published', true);6});7User::doesntHave('posts');
Package implementations using joins
1User::powerJoinHas('posts');2User::powerJoinHas('posts.comments');3User::powerJoinHas('posts.comments', '>', 3);4User::powerJoinWhereHas('posts', function ($query) {5 $query->where('posts.published', true);6});7User::powerJoinDoesntHave('posts');
Sorting your query results
Another useful feature os to sort your query results using a column from another table using the orderByPowerJoins
method.
1User::orderByPowerJoins('profile.city')->toSql();2// select "users".* from "users"3// inner join "user_profiles" on "user_profiles"."user_id" = "users"."id"4// order by "user_profiles"."city" asc
You can also sort your results by aggregations (COUNT
, SUM
, AVG
, MIN
or MAX
).
For instance, to sort users with the highest number of posts, you would do this:
1$users = User::orderByPowerJoinsCount('posts.id', 'desc')->get();
Or, to get the list of posts sorted by the ones with comments which contain the highest average of votes.
1$posts = Post::orderByPowerJoinsAvg('comments.votes', 'desc')->get();
And you also have methods for SUM
, MIN
and MAX
:
1Post::orderByPowerJoinsSum('…');2Post::orderByPowerJoinsMin('…');3Post::orderByPowerJoinsMax('…');
Joins, the Laravel way
IMO, one of the advantages of the package is being able to write code in a more “Laravel way”. So, below you can see a few examples of how much better the code looks after using it. Any examples described here produces the EXACT same result.
Example 1
1BuilderFile::select('builder_detail_builder_file.*')2 ->join('builder_detail_builder_file', 'builder_files.id', '=', 'builder_detail_builder_file.builder_file_id')3 ->join('builder_details', 'builder_details.id', '=', 'builder_detail_builder_file.builder_detail_id')4 ->join('documents', 'builder_details.document_id', '=', 'ces_documents.id');
With Eloquent Power Joins
1BuilderFile::joinRelationship('details.document');
Example 2
1CesDocument::query()2 ->join('term_relations', function ($join) {3 $join4 ->on('term_relations.relationable_id', '=', 'ces_documents.id')5 ->where('term_relations.relationable_type', '=', CesDocument::class);6 })7 ->join('terms', 'term_relations.term_id', '=', 'terms.id')8 ->join('vocabularies', 'terms.vocabulary_id', '=', 'vocabularies.id')9 ->get();
With Eloquent Power Joins
1CesDocument::query()2 ->joinRelationship('related.terms')3 ->joinRelationship('related.vocabulary')4 ->get();
That's it. Hopefully this package is going to be as useful to you as it is to us. Happy joining!
0 comments:
Post a Comment
Thanks