John Davidson

php - the more optimized way to get data from database in laravel

0 comments
Message:


I'm working on a news website which on home page I have to show 3 items from each category and there are alike 20 categories. What I have tried:


$politicals = News::whereHas('categories', function ($q) {
$q->where('categories.slug','politics');
})->orderBy('created_at','desc')->take(3)->get();

$economical = News::whereHas('categories', function ($q) {
$q->where('categories.slug','economical');
})->orderBy('created_at','desc')->take(3)->get();

$conversation = News::whereHas('categories', function ($q) {
$q->where('categories.slug','conversation');
})->orderBy('created_at','desc')->take(3)->get();

$socialMedia = News::whereHas('categories', function ($q){
$q->where('categories.slug','socialMedia');
})->orderBy('created_at','desc')->take(3)->get();

Consider that I have a manyToMany relationship on categories and if the number of news goes high like 2000 news the home page I think would be really slow and I think that I cant use cache because news change like every 5 or more minutes. So I wanted to know if there is any better way to do some repeatable queries like mine . thanks in advance



My Answer:
>where('name', 'political');_})->take(3)->get();$sports = News::whereHas('categories', function ($q) {_ $q->where('name', 'sports');_})->take(3)->get();$entertainment = News::whereHas('categories', function ($q) {_ $q->where('name', 'entertainment');_})->take(3)->get();_// Repeat this for all categories and then pass these variables to the viewreturn view('home', compact('politicals', 'sports', 'entertainment', ...));_This approach works but it is not optimized as it makes multiple queries to the database. A more optimized way to achieve this is to use eager loading and group the results by category. Here's how you can do it:_$news = News::with('categories')->get()->groupBy('category_id');_// Now you can loop through the $news variable in your view to display the news itemsforeach ($news as $category => $items) {_ $items = $items->take(3); // Limit to 3 items per category // Pass $items to the view for each category}_This way, you only make one query to the database and group the results by category, making it more efficient.

Rate this post

4 of 5 based on 9569 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us