Created
October 24, 2023 16:59
-
-
Save MrPunyapal/db277beb047bc52e5ff899071aac38c5 to your computer and use it in GitHub Desktop.
π Laravel Tip: Optimize Queries with withAggregate π
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// In the Post model | |
class Post extends Model | |
{ | |
public function user() | |
{ | |
return $this->belongsTo(User::class); | |
} | |
} | |
// To Load posts with user data using with Sposts | |
Post::with('user:id, name')βtake (3)βget(); | |
// SQL queries: | |
// select * from posts limit 3; // select id, 'name' from users where users. id in (1, 2, 3); | |
// Access user's name using user name! | |
$name = $posts first()βuser name; | |
// To load posts with user's name aggregated using withAggregate' | |
$posts = Post::withAggregate('user', 'name')βtake (3)βget(); | |
// SQL query: | |
// select 'posts,*, (select name from 'users' where 'posts","user_id` = // as "user_name from 'posts' Limit 3; | |
// Access user's name using βuser_name' | |
$name = $posts first()βuser_name; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment