PHPize Online / SQLize Online

A A A
Share      Blog   Popular
Copy Format Clear
create table products ( id int, name varchar(64) ); insert into products values (1, 'Pr 1'); insert into products values (2, 'Pr 2'); create table product_reviews ( id int, product_id int, star_rating int ); insert into product_reviews values (1, 1, 3); insert into product_reviews values (2, 4, 3);
Copy Clear
Copy Format Clear
<?php // Select using Laravel $products = $db::table('products') ->leftJoin('product_reviews', 'product_reviews.product_id', '=', 'products.id') ->select( 'products.id', $db::raw("IF(SUM(product_reviews.star_rating) != 0, SUM(product_reviews.star_rating) / COUNT(product_reviews.id), 0) AS rate") ) ->groupBy('products.id') // ->havingBetween('rate', [4, 5]) ->get(); echo($products);
Show:  
Copy Clear