Joining multiple tables and building a search page using Eloquent in Laravel 4

Tags

, , ,

Scenario

I want to build a vehicle search page. Vehicles data consists on six tables. Following are tables the stores all vehicles information.

  • Listings
  • Photos
  • Makers
  • Models
  • Locations
  • Users

On my search page I have to show complete information of a vehicle. See below ER Diagram with relations.

Vehicle Search ERD

Vehicle search ER Diagram

Eloquent Statement

$results = Vehicle::select(‘listings.*’,’photos.path’,’makers.name as makername’,
‘models.name as modelname’,
‘locations.name as cityname’,  ‘users.firstname’)
->join(‘photos’, ‘listings.id’, ‘=’, ‘photos.listing_id’)
->orderBy(‘photos.id’, ‘desc’)
->join(‘makers’, ‘listings.make_id’, ‘=’, ‘makers.id’)
->join(‘models’, ‘listings.model_id’, ‘=’, ‘models.id’)
->join(‘locations’, ‘listings.location_id’, ‘=’, ‘locations.id’)
->join(‘users’, ‘listings.user_id’, ‘=’, ‘users.id’)
->where(‘makers.name’,’=’, ‘BMW’)
->where(‘models.name’,’=’, ‘3 Series’)
->where(‘locations.name’,’=’, ‘London’)
->groupBy(‘listings.id’)
->paginate(15);