MN relationships in Doctrine
ZF has a very nice feature which is called findManyToManyRowset which returns you directly a collection of objects from a MN connection. The whole purpose of MN is to get the information from the other table, not from the connection table.
We have this schema:
- users
- id
- name
- groups
- id
- name
- user_has_groups
- user_id
- group_id
I want to create a user function that will return directly a collection of group objects and not a collection of user_has_groups objects.
$user->UserHasGroups ;// returns a collection of user_has_groups
$user->Groups; // returns Doctrine_Record_UnknownPropertyException
Is there a way 开发者_高级运维to do this directly?
Doctrine handles this automatically assuming your schema is set up correctly. I only use Doctrine as part of Symfony, so my schema.yml
would look something like this. You may need to alter it if your Doctrine install uses a different method to define your schema:
Users:
columns:
name:
type: string
relations:
Groups:
refClass: UserHasGroups
local: user_id
foreign: group_id
Groups:
columns:
name:
type: string
relations:
Users:
refClass: UserHasGroups
local: group_id
foreign: id
UserHasGroups
columns:
user_id:
type: integer
primary: true
group_id:
type: integer
primary: true
Doctrine will use the UserHasGroups
class as a many-to-many join table. Then, calling $user->Groups
will get you all associated Groups
objects.
As a side note, I would change your model names to the singular form, eg User
, Group
. $user = new Users()
implies at first glance that you're creating multiple users in one go, which I presume you're not :-)
See the Doctrine join table docs for further details.
精彩评论