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.ymlwould look something like this. You may need to alter it if your Doctrine install uses a different method to define your schema:Doctrine will use the
UserHasGroupsclass as a many-to-many join table. Then, calling$user->Groupswill get you all associatedGroupsobjects.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.