开发者

PHP doctrine many-to-many last identifier problem

I have small problem when trying to create many-to-many link in doctrine.

I have simple scenario here: User and Role with many-to-many relationship defined.

$user = new User();
$user->username = 'greg';
$user->save();


$role = new Role();
$role->name = "Administrator";
$role->save();

$role_user = new Role_User();
$role_user->Role = $role;
$role_user->User = $user;
$role_user->save();

Now, I did some experiments and I can save user and role on it's own without any problems. They both have autoincrement ids and it works fine. The problem starts when I want to create relationship with exception saying 'Couldn't get last insert identifier'.

I can't change DB schema and I was not generating it via YAML - I reverse engineered models from existing DB via 'generateModelsFromDb'. This is how this table looks like:

CREATE TABLE  `ofp`.`Role_User` (
   `roles_id` bigint(20) NOT NULL,
   `users_id` bigint(20) NOT NULL,
   KEY `FK8B6B91F429A30245` (`roles_id`),
   KEY `FK8B6B91F429A6266F` (`users_id`),
   CONSTRAINT `FK8B6B91F429A6266F` FOREIGN KEY (`users_id`) REFERENCES `User` (`id`),
   CONSTRAINT `FK8B6B91F429A30245` FOREIGN KEY (`roles_id`) REFERENCES `Role` (`id`)
 ) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Error I'm getting would suggest there is something wrong with creating primary key identifier to this table, but I'm not sure I need one there (Maybe unique key to eliminate duplicates?).

Does 开发者_如何学编程anybody have any clues?


Setting refClass is mandatory in many-to-many relationships


You shouldn't even use Role_User object directly. Note that it's only a part of your db-schema, not object interface.

$role = new Role();
$role['name'] = 'role name';
$role->name   = 'role name';
$role->setName('role name'); // That won't work unless you're using Doctrine with
                             // Symfony (just notice)
$role->set('name', 'role name');

$user = new User();
$user['username'] = 'username';
$user['Roles'][] = $role;

$user->save();

That should save user object, then role and finally create relationship between them.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜