Search code examples
phpsymfonysonata-adminsymfony-sonatasonata-user-bundle

symfony, sonta user bundle, many to many


I'm doing a little project, in which I use sonata user bundle to administrate easily my users.

But I have another entity who is named order. In this entity is linked with one user. Where have I to write the manyToOne anotation?

Thanks Best regards


Solution

  • If you are using sonata admin then you can easily extend its core bundles using EASYEXTENDS BUNDLE it will generate a child bundle e.g

    php app/console sonata:easy-extends:generate SonataUserBundle -d src Reference

    Once you have extended bundle for SonataUserBundle you can specify your relations in child bundle's entity or its doctrine config file

    <?xml version="1.0" encoding="UTF-8"?>
    <doctrine-mapping xmlns="http://doctrine-project.org/schemas/orm/doctrine-mapping"
                      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                      xsi:schemaLocation="http://doctrine-project.org/schemas/orm/doctrine-mapping
                      http://doctrine-project.org/schemas/orm/doctrine-mapping.xsd">
        <entity name="Application\Sonata\UserBundle\Entity\User" table="fos_user_user">
            <id name="id" column="id" type="integer">
                <generator strategy="AUTO" />
            </id>
            <one-to-many  field="orders" target-entity="Order" mapped-by="user" />
        </entity>
    </doctrine-mapping>
    

    In your user entity

    use Doctrine\Common\Collections\ArrayCollection;
    use Sonata\UserBundle\Entity\BaseUser as BaseUser;
    class User extends BaseUser
    {
        protected $orders;
        public function __construct()
        {
            $this->orders= new ArrayCollection();
        }
    //.. Getter and setter
    }
    

    In your order entity add mapping to point back to user entity

    class Order
    {
        protected $user;
    }
    

    In order doctrine config file define mapping to user entity

    <many-to-one  field="user" target-entity="User" inversed-y="orders" join-column="user_id">
    

    If you are using annotations you can find equivalent mapping from Docs