vendredi 30 septembre 2016

MySQL sub query in Laravel, how to join queries and add second query's result as a new column to first query?

I have two tables:

- PRODUCTS (having: ID, NAME, PRICE)
- LIKES (having: ID, PRODID, NAME)

I would like to query the first table while counting (and returning as a new column) in a sub query all the likes the product has. How could I combine the following queries?

$products = DB::table('PRODUCTS')
                  ->get();

$likes = DB::table('LIKES')
                  ->select(DB::raw('count(*) as total'))
                  ->where('PRODID', '=', 'product id from first table')
                  ->get();

How could I achieve this using Laravel queries? Thanks!



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire