[Vuejs]-Fetching has many relationship data Laravel and using avg function

0๐Ÿ‘

โœ…

You may do it this way:

public function getAllReviews(Request $request)
{
    $reviews = Review::selectRaw('*, IFNULL((SELECT AVG(rating) FROM ratings where ratings.review_id = reviews.id), 0) as avg_rating')->get();

    return $reviews;
}
๐Ÿ‘คAakash Tushar

0๐Ÿ‘

I would suggest using the basic relationship and a modified withCount():

public function ratings() {
    return $this->hasMany('App\Rating');
}

$reviews = Review::withCount(['ratings as average_rating' => function($query) {
    $query->select(DB::raw('coalesce(avg(rating),0)'));
}])->get();

0๐Ÿ‘

public function showProduct($id)
    {   

        $data = Product::where('category_id',$id)
                ->selectRaw('*, IFNULL((SELECT AVG(value) FROM ratings where ratings.product_id = products.id), 0) as avg_rating')
                ->get();

        return view('ecommerce.web.productsOfcategory',compact('data'));
    }
๐Ÿ‘คch_abid

0๐Ÿ‘

$avgQuery = "IFNULL((SELECT AVG(ratings.rating) FROM ratings WHERE ratings.review_id = reviews.id),'No Ratings') as avg_rating";

$reviews = Review::query()->selectRaw("reviews.*, $avgQuery")->get();

//SQL Query
$sqlQuery = "select reviews.*, IFNULL((SELECT AVG(ratings.rating) FROM ratings where ratings.review_id= ratings.id), 'No ratings') as avg_rating FROM reviews";
๐Ÿ‘คfreskimi

Leave a comment