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
Source:stackexchange.com