jeudi 5 juillet 2018

Fetching has many relationship data Laravel and using avg function

I am using Laravel 5 with vue js. Basically i am fetching data using axios and trying to display on the webpage using vue js v-for directive. i have tables in database like this:

ratings Table

id review_id rating

Then i have a

reviews table

id review

They have one to many relationship between. so here in my Review Model i have method

 public function ratings()
    {
        return $this->hasMany('App\Rating')
            ->selectRaw('review_id,AVG(rating) AS average_rating')
            ->where()
            ->groupBy('review_id');
    }

so here i want to fetch list of reviews with their average ratings. so in my controller i am doing this:

  public function getAllReviews(Request $request)
    {
        $reviews = Review::with('ratings')->get();

        return $reviews;
    }

So i am getting result but the problem is every review doesnt have ratings record so it is returning null? maybe... when i try to render in vue template it throws an error undefined because in our collection some reviews do not have ratings.

Now my question is: Can i do something like if there is no record in the ratings for a particular review is it possible to add an array with value 0?? so in my frontend it wont see as undefined.

I hope i am successful to explain i am trying.

Thank you.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire