Search code examples
phpmysqldoctrine-ormmappingrelationships

oneToMany or manyToOne Doctrine2 relationship


I have the following situation.

I have a clients table and services table.

case 1 What I want is to know how to make a submit form in Symfony2 (actually I think that if you can guide me only in YML mapping is enough) that can CRUD a clients entity, which it can has X services assigned to it.

clients table only has id and nombre columns, same as services.

case 2 Then, once this is done, I have a new table called task this new table needs to have the following:

A client for the task. A service for the task, which, at the same time needs to be assigned to that client, so it is dependent from client select box (I can make this with jQuery) And some oneToOne relationships which are actually working very well.

If the task has more than one client, it would be great if I could add on the same form using prototype with forms collection or something a new client, and of course, a new service if needed... But this is totally optional, what I'm really lost is in case 1, because I think if someone could help me with case 1, case 2 will be easy to make on my own...

And of course, I don't know what to use, oneToMany or manyToOne in both cases...


Solution

  • i strongly recommend this:

    http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/association-mapping.html

    but to make the long story short here is your YAML for case1 if you want a bidirectional relation:

    Client:                          // dont forget namespace
      type: entity                  
      table: client
      id:
        id:
          type: integer
          generator: { strategy: AUTO }
      fields:
        number:
          type: integer
      oneToMany:                        // each client has many services
        services:                       // the variable to store services of client
          targetEntity: Service
          mappedBy: client              // the variable to store client of a service
    Service:
    ...                                 //same as above
      manyToOne:
        client:
          targetEntity: Client 
          inversedBy: services         
    

    i didnt understood the case2 properly.