I have a "answers" table and a "users" table. I need to link them but I have to use custom keys on both tables (i.e. I'm not using 'id' in any of them). Both tables have the "facebook_id" field which connects them.
In the Answer model I define a "belongs_to" User, and I can define Answer's foreign_key, but how can I say "link Answer to User using facebook_id on both tables"?
It appears the only way this is possible is by changing your models _primary_key
to facebook_id
Upon investigation of the ORM class structure you'll see the tables are joined like so
elseif (isset($this->_belongs_to[$column]))
{
$this->_load();
$model = $this->_related($column);
// Use this model's column and foreign model's primary key
$col = $model->_table_name.'.'.$model->_primary_key;
$val = $this->_object[$this->_belongs_to[$column]['foreign_key']];
$model->where($col, '=', $val)->find();
return $model;
}
As you mentioned you can use
protected $_belongs_to = array('user' => array('foreign_key' => 'facebook_id')
But that would result in
answers.id = users.facebook_id
But if you change the primary key on answers from id to facebook_id like so
protected $_primary_key = 'facebook_id';
Then of course the final query would result in
answers.facebook_id = users.facebook_id