Yoot
Yoot

Reputation: 657

Symfony 2 : Doctrine OneToMany relation

I've 2 entities :

class Client
{
    /**
     * @var integer $mainId
     *
     * @ORM\Column(name="main_id", type="integer", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $mainId;

    /**
     * @var string $id
     * 
     * @ORM\Column(name="id", type="string", length=10, nullable=false, unique=true)
     */
    private $id;

    ...
}

class Child
{
    /**
     * @var integer $id
     *
     * @ORM\Column(name="id", type="integer", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $id;

    /**
     * @var Client
     *
     * @ORM\ManyToOne(targetEntity="Client")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="client_id", referencedColumnName="id")
     * })
     */
    private $clientId;

    ....
}

For some reason the foreign key from the child table doesn't point to the primary key of the Client table, but anyway I don't think that it should be a problem.

When I try to do the following action in my controller :

$child->set...
$child->setClientId($client);
$em->persist($child);

I get the following error :

Notice: Undefined index: id in C:\wamp\www\myApp\vendor\doctrine\lib\Doctrine\ORM\Persisters\BasicEntityPersister.php line 510 

I tried to add @Index anntotation in my Client Table but I still get the error...

I've never had that problem before, any help would be welcome.

EDIT

If I move the "@ORM\Id" annotation from $mainId to $id in my Client class, that works. Would that mean that Doctrine 2 doesn't allow foreign keys that points on 'non primary key' fields ?

Upvotes: 0

Views: 3284

Answers (2)

Confidence
Confidence

Reputation: 2303

why don't you simply design everything on your Database, including foreign keys, and so on...and simply create your Entities based on the database using this here?

http://symfony.com/doc/current/cookbook/doctrine/reverse_engineering.html

worked perfectly for me.

Upvotes: 0

Inoryy
Inoryy

Reputation: 8425

referencedColumnName should be set to the column that has @ORM\Id set, so in your case referencedColumnName="main_id" should work

(don't forget to clear cache and run doctrine:schema:update --force after you change these settings)

Upvotes: 1

Related Questions