I'm new to Laravel and Eloquent and am trying to retrieve unique records, from 3 tables, namely cupboards, item_types, and a pivot cupboard_items. There is also a 4th location table.
Constructed a working query in MySQL as below (tested successfully on MySQL workbench). Tried using DB::raw('') and DB::statement(''), but my IDE gave a warning that 'No data sources are configured to run this SQL and provide advanced code assistance' and using DB::raw returned an empty object while DB::statement returned 'true'.
SELECT cupboards.cupboard_id, cupboards.name, cupboards.capacity, dist.item_type_id, item_types.name, locations.coordinates FROM cupboards INNER JOIN
(SELECT DISTINCT cupboard_items.item_type_id, cupboard_id FROM cupboard_items) AS dist
ON cupboards.cupboard_id = dist.cupboard_id
INNER JOIN item_types ON dist.item_type_id = item_types.item_type_id
INNER JOIN locations ON locations.location_id = cupboards.location_id;
Not sure whether my syntax is wrong, but I subsequently also tried to construct a Eloquent query
$result = DB::table('cupboards')
->select(DB::raw('cupboards.cupboard_id, cupboards.name, cupboards.capacity, dist.item_type_id, item_types.name, locations.coordinates'))
->join(DB::raw('SELECT DISTINCT cupboard_items.item_type_id, cupboard_id FROM cupboard_items'))
->join('item_types', 'dist.item_type_id', '=', 'cupboard.item_type_id')
->join('locations', 'locations.location_id', '=', 'cupboards.location_id')
->get();
But apparently I can't have DISTINCT in my DB::raw query statement, and am not sure whether my join is done correctly. Any advice on how to proceed from here is much appreciated!!! Thanks!