Skip to content

Instantly share code, notes, and snippets.

@MrPunyapal
Created October 24, 2023 16:59
Show Gist options
  • Save MrPunyapal/db277beb047bc52e5ff899071aac38c5 to your computer and use it in GitHub Desktop.
Save MrPunyapal/db277beb047bc52e5ff899071aac38c5 to your computer and use it in GitHub Desktop.
πŸš€ Laravel Tip: Optimize Queries with withAggregate πŸ“Š
<?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