I need help constructing a CodeIgniter Datamapper ORM query that includes join fields.
I have a table of Merchants and a table of Vendors.
They have a many-to-one relationship, that is, many Merchants are part of a single Vendor.
Thus, my datebase tables, following the Datamapper ORM convention are:
merchants
vendors
merchants_vendors
Furthermore, in the merchants_vendors table, I have join fields ‘role’ and ‘admin’.
Obviously, this data must be placed in the join table, if it were placed in the Merchants table, I wouldn’t be able to define roles and administrators per Vendor.
Lastly, Merchants are related to Users by a one-to-one relationship.
Think of Merchants as just an extension of Users.
I’m attempting to create a PHP array from the data that follows this data structure, but I can’t seem to get the role and admin fields populating properly. I removed redundant columns for your simplicity:
[vendor] => Array
(
[id] => 1
[name] => Vendor1
[users] => Array
(
[0] => Array
(
[id] => 277
[username] => merchant1
[firstname] => Merchant1
[merchant] => Array
(
[id] => 1
[user_id] => 277
[role] => Sales
[admin] => 0
)
)
[1] => Array
(
[id] => 282
[username] => merchant2
[firstname] => Merchant2
[merchant] => Array
(
[id] => 2
[user_id] => 282
[role] => Software
[admin] => 1
)
)
)
)
Here’s the code I’m using – Assuming we know the Vendor ID:
$v = new Vendor($id);
if($v->exists())
{
$d['vendor'] = $v->to_array();
$m = new Merchant();
$m->where_related_vendor('id', $v->id)->get();
if($m->exists())
{
foreach($m as $mK => $mV)
{
$u = new User();
$u->where_related_merchant('id', $mV->id)->get();
$d['vendor']['users'][$mK] = $u->to_array();
$d['vendor']['users'][$mK]['merchant'] = $mV->to_array();
}
}
}
$this->load->view('myview', $d);
This gets me as far as the above PHP data structure without the role and admin.
I am well aware of the include_join_fields() function – but I cannot seem to get it working. Specifically, I tried $m->vendor->include_join_fields(); Then tried to access the role/admin fields by $mV->vendor->join_role and $mV->vendor->join_admin – but that doesn’t work.
Your help is much appreciated!
The solution was to use include_join_fields() on the $mV object inside the forloop:
Ongoing discussion in the CodeIgniter forums.
I will post more information as it arrives.