Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Primary key and foreign key at the same time with doctrine 2

I have the two tables :

table A with id as primary key

table B with id as primary key and foreign key

Explanation on short:

I need to have in table B a primary key that also to be a foreign key that points to table A's primary key.

Can anybody explain me how to map this by annotations in Doctrine 2?

Note:

I tried it By this :

   class A
{
    /**
     * @var bigint $id
     *
     * @Column(name="id", type="bigint", nullable=false)
     * @Id
     * @GeneratedValue(strategy="IDENTITY")
     */
    private $a_id;
...

and B table:


class B
{
    /**
     * @var bigint $id
     * @Id 
     * @OneToOne(targetEntity="A", fetch="LAZY")
     * @JoinColumn(name="id", referencedColumnName="id")
     */
    private $b_id;
...

But it gives me this error:

Uncaught exception 'Doctrine\ORM\Mapping\MappingException' with message 'No identifier/primary key specified for Entity 'B'. Every Entity must have an identifier/primary key.' in /var/www/agr-reg-php/Doctrine/ORM/Mapping/MappingException.php:37 Stack trace:

N.B: I must not have composite primary key.

like image 432
artaxerxe Avatar asked Jun 17 '11 09:06

artaxerxe


1 Answers

This is possible since Doctrine 2.1:

Identity through Foreign Entities or derived entities: You can now use a foreign key as identifier of an entity. This translates to using @Id on a @ManyToOne or @OneToOne association. You can read up on this feature in the tutorial.

like image 108
Ondřej Mirtes Avatar answered Oct 31 '22 20:10

Ondřej Mirtes