I am using MY_model as is Codeigniter-base-model. I am unable to get the basic relationship working. I searched a lot but could find solution.
To start with I have 2 classes item_model.php
& user_model.php
both extend MY_Model.
In item_model
class I have defined
public $belongs_to = array( 'user' => array( 'model' => 'user_model') );
and in the user_model
public $has_many = array( 'items' => array( 'model' => 'item_model') );
Now, in the controller when I call
$item_details = $this->item_model->with('user')->find_by_id($item_id);
I am getting the correct data for $item_details
but I am unable to get information from the 'user' relationship. $item_details->user_id->username;
.
I am getting following error
Message: Trying to get property of non-object
Table are standard
users table has id, username, ...
item table has id, user_id, title...
user_id is is setUp as FK to users.id.
Please help.
if you check source code of relate() method, you will found this piece of the code:
if (is_string($value))
{
$relationship = $value;
$options = array( 'primary_key' => $value . '_id', 'model' => $value . '_model' );
}
else
{
$relationship = $key;
$options = $value;
}
I check the source code, if you use a array to define the model, you need to define 'primary_key' as well, this is not in document.
'primary_key' means which foreign key of this table to link my primary_key.
public $belongs_to = array( 'user' => array( 'model' => 'user_model','primary_key'=>'user_id') );
will be more right.