CodeIgniter DataMapper ORM v1.8.0 - How to Get records from multiple tables CodeIgniter DataMapper ORM v1.8.0 - How to Get records from multiple tables codeigniter codeigniter

CodeIgniter DataMapper ORM v1.8.0 - How to Get records from multiple tables


Here's one simple way, assuming you have one-to-one relationship:

In your Model Driver:

var $has_one = array('vehicle');

In your Model Vehicle:

var $has_one = array('driver');

To get a vehicle and its driver:

$v = new Vehicle();$v->include_related('driver')->get();

include_related() will only work with $has_one related models.

Driver's properties are now stored in $v with the prefix driver_. To access the vehicle's driver columns:

echo $v->driver_first_name;echo $v->driver_last_name;

Alternatively, you can auto-load the driver every time you access the vehicle:

// In Vehiclevar $auto_populate_has_one = TRUE;

For has-many relationships, you can do this:

$d = new Driver();$d->get_by_id($id);// Get a driver by idforeach ($d->vehicle->get() as $car){    // Print all this Driver's vehicles    echo $car->vehicle_model;}

This is just one way to do it. There are so may ways to access relationships in Datamapper, your best bet is to read the documentation thoroughly, then read it again. Datamapper is a great ORM and you should learn and experiment with all it's features to get the most out of it.


This could be a good opportunity to use a Foreign Key in your Drivers Table. Here is a link to the MySQL documentation on using Foreign Keys in your table: MySQL Foreign Keys

Alternatively if you don't want to deal with the hassles of advanced MySQL calls you could also just process two queries, one to your vehicles table, and one to your drivers table, and then use PHP to iterate (loop) through the results until you can find and match the correct values with each other.

Actually both ways are probably a bit of a hassle to set up, but your foreign key would likely be the easier to maintain.