phpcodeignitercodeigniter-datamapper

Proper Method For Setting Up One-to-One in CodeIgniter Datamapper


I am reviewing all of my models and corresponding tables for CodeIgniter Datamapper. I'm wondering what the correct way of setting up a one-to-one relationship with a defined parent and child is. The way I have been doing it is similar to this:

class Customer ... {

  public $has_one = array('address');

}

class Address ... {

  public $has_one = array('customer');

}

with the Customer being the parent (ie, has either one or zero Addresses) and the address being the child (always has one Customer). In the database I have a customer_id on addresses which is not null, indexed and associated with customer.id and set to CASCADE on update and delete , and address_id on customers which is null and associated with address.id and set to NO ACTION on update and delete.

Is this the proper configuration for a CI Datamapper one-to-one-or-zero (parent/child) relationship?


Solution

  • There is a good explanation in the FAQ section of the docs:

    When configuring a relationship, even a self-relationship, you must define both "sides" of the relationship. This means for a parent/child relationship, you have to specify the parent on the child, and you have to specify the child on the parent. Here is an example for a complex self-relationship [User (as Boss) has many Employees, and Employees have one Boss]:

    // In User
    $has_one = array(
        // define the relationship to the boss
        'boss' => array(
            'class' => 'user',
            'other_field' => 'employee'
        )
    );
    
    $has_many = array(
        // define the relationship to the employees
        'employee' => array(
            'class' => 'user',
            'other_field' => 'boss'
        )
    );