Kohana 3.2 ORM many-to-many – wrong field names-Collection of common programming errors
I trying to make many-to-many relation between 2 models: Users_Role and Users_Right
class Model_Users_Role extends ORM{
protected $_has_many = array(
'rights' => array(
'model' => 'users_right',
'through' => 'users_roles_rights',
),
);
}
class Model_Users_Right extends ORM{
protected $_has_many = array(
'roles' => array(
'model' => 'users_role',
'through' => 'users_roles_rights',
),
);
}
I’m trying to do this:
$role = ORM::factory('users_role', 1);
$right = ORM::factory('users_right', 1);
$right->add('roles', $role);
Error:
Database_Exception [ 1054 ]: Unknown column 'role_id' in 'field list' [ INSERT INTO `users_roles_rights` (`users_right_id`, `role_id`) VALUES ('1', '1') ]
I tryed to make it on the other side:
$role = ORM::factory('users_role', 1);
$right = ORM::factory('users_right', 1);
$role->add('rights', $right);
New error:
Database_Exception [ 1054 ]: Unknown column 'right_id' in 'field list' [ INSERT INTO `users_roles_rights` (`users_role_id`, `right_id`) VALUES ('1', '1') ]
I expected ORM to use users_role_id
and users_right_id
field names in pivot table, but it uses wrong name of far key? Where I have made a mistake?
-
Check out where the default values are set. Try this:
class Model_Users_Role extends ORM{ protected $_has_many = array( 'rights' => array( 'model' => 'users_right', 'far_key' => 'users_right_id', 'through' => 'users_roles_rights', ), ); } class Model_Users_Right extends ORM{ protected $_has_many = array( 'roles' => array( 'model' => 'users_role', 'far_key' => 'users_role_id', 'through' => 'users_roles_rights', ), ); }
Kohana does not check that the relationship does not already exist.
Either enforce this in the database table with a composite unique key on the two foreign key columns, or make your code check that the relationship does not already exist before adding.
Originally posted 2013-11-27 11:53:26.