Datamapper with existing database- tables with primary key column name other than id

509 views Asked by At

I am running a application using codeigniter framework. I have a database. I want to implement datamapper ORM. Since for datamapper- "Every table must have a primary key named id".

I have an auto increment integer field in all tables. But the column name is not "id" in all cases. In my user table, the auto-increment integer column name is user_id instead of id. What changes do i need to make to work with Datamapper ?

A Database Error Occurred

Error Number: 1054

Unknown column 'id' in 'where clause'

SELECT *
FROM (`user`)
WHERE `id` =  200

Filename: D:\Projects\DealVector\dealvector\system\database\DB_driver.php

Line Number: 330
1

There are 1 answers

0
piyush On BEST ANSWER

I didn't find any solution apart from editing the native datamapper library. I modified the function _get_by() in datamapper class in /application/libraries/datamapper.php as below. i added var $table = 'user'; var $id = 'user_id'; in my model and added if($field=='id'){ $field = $this->id; } in datamappper library.

/**
 * Get By
 *
 * Gets objects by specified field name and value.
 *
 * @ignore
 * @param   string $field Field to look at.
 * @param   array $value Arguments to this method.
 * @return  DataMapper Returns self for method chaining.
 */
private function _get_by($field, $value = array())
{
    //Custom Change
    if($field=='id'){
        $field = $this->id;
    }

    if (isset($value[0]))
    {
        $this->where($field, $value[0]);
    }

    return $this->get();
}