Search code examples
phpcodeigniterormdatamappercodeigniter-datamapper

Using DataMapper ORM and Codeigniter to select join table value in a many to many relationship


I have this table structure:

| users | --- has many > --- | preferences_users | --- < has many --- | preferences |

A preference could be something like "first name" or "surname" but the value for these preferences are stored in the joining table.

I am using Codeigniter and Datamapper ORM to get relational tables into objects, however I am not sure how to get this value in the joining table.

I am doing this:

$user = new User();
$user->where('unique_url', $url)->get();
$user->preferences->get_iterated();

My relationships are set up so that they both have $has_many = array('tablename'); and I am able to get the values from each table.

HOwever I want to be able to get a table column value from the joining table, does anyone know how to do this?

Thanks,

Ian


Solution

  • I found the answer in the documentation:

    $object->include_join_fields()

    There are no options for this method. Set it right before adding a relationship. You can either use it before a {$query}_related_{$model}, or before calling get() on a related item. All fields on the table that are not part of the relationship are included, and are prepended with "join_".

    This method may return unexpected results or throw errors with deep relationships.

    Usage:

    // Create User $u = new User(); $u->get_by_id($userid);
    
    // get all alarms for this user, and include the extra 'wasfired'
    field $u->alarm->include_join_fields()->get();
    
    foreach($u->alarm as $alarm) {
        if($alarm->join_wasfired) {
            echo("{$alarm->name} was fired\n");
        } else {
            echo("{$alarm->name} was NOT fired\n");
        }
    }
    

    See Working with Join Fields for more details.