Farshad
Farshad

Reputation: 2000

the more optimized way to get data from database in laravel

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

Upvotes: 0

Views: 170

Answers (1)

Hanan Alhasan
Hanan Alhasan

Reputation: 300

you can write the query like this

$news = Category::with(['news' => function($q){
        $q->take(3);
    }])->get();

this query will get you all categories and each category with 3 news

you also need to define the relations in the models

in Category.php

public function news()
{
    return $this->belongsToMany(News::class);
}

Upvotes: 1

Related Questions