简体   繁体   中英

Doctrine: Many-to-Many without Join Table on Legacy Database

My question is essentially this one , only I am using Doctrine 2 instead of Hibernate. I'm given this (simplified) DB structure:

PRODUCT                      TABLE_ENTRY
-------                      -----------
ID int primary key           ID int primary key
NAME varchar                 IDX int
GROUPING_CODE varchar(32)    GROUPING_CODE varchar(32)
  • GROUPING_CODE is not unique in both tables
  • Each TABLE_ENTRY is associated with n PRODUCTs

I would like to map this relation in one direction, as described in the answer to said Hibernate question:

/**
 * @ORM\OneToMany(targetEntity="Product")
 * @ORM\JoinColumn(name="grouping_code", referencedColumnName="grouping_code")
 */
private $products;

In Doctrine this does not seem to work, because the " mappedBy " attribute is required by OneToMany . Is there an other way to achieve a similar mapping in Doctrine? Read-only would be sufficient, too.

In the meantime I found a solution that seems to be working and might be sufficient in my case:

/**
 * @ORM\ManyToMany(targetEntity="Product")
 * @ORM\JoinTable(name="product",
 *        joinColumns={
 *            @ORM\JoinColumn(name="grouping_code", referencedColumnName="grouping_code")},
 *        inverseJoinColumns={
 *            @ORM\JoinColumn(name="id", referencedColumnName="id")}
 *      )
 */
private $products;

Essentially, this is using the target table PRODUCT itself (again) as the join table.

This does feel like a hack and probably is, but it seems to be doing what is required. I am sure it would fail utterly when used to write to the database, though.

Update: One huge draw-back of this solution is that DB schema update, creation, and dump won't work because Doctrine complains that the table PRODUCT already exists.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM