Doctrine2: undefined index - many-to-one with no default defaultColumnName does not save the object

I am using Symfony 2.1.2.

I have two entities and define the relationship between them [many-to-one (bidirectional]] (1). I do not want to use the primary key for the foreign key (referatedColumnName). I want to use another integer unique column: customer_no

/** * @ORM\Entity * @ORM\Table(name="t_myuser") */ class MyUser extends BaseEntity // provides an id (pk) { /** * @ORM\ManyToOne(targetEntity="Customer", inversedBy="user") * @ORM\JoinColumn(name="customer_no", referencedColumnName="customer_no", nullable=false) */ public $customer; } /** * @ORM\Entity * @ORM\Table(name="t_customer") */ class Customer extends BaseEntity // provides an id (pk) { /** * @ORM\Column(type="integer", unique=true, nullable=false) */ public $customer_no; /** * @ORM\OneToMany(targetEntity="MyUser", mappedBy="customer") */ public $user; } 

When I try to save the MyUser object with the Customer object, I get this error:

Note: Undefined index: customer_no in ... \ vendor \ doctrine \ orm \ lib \ Doctrine \ ORM \ Persisters \ BasicEntityPersister.php line 608

The db schema looks great, these should be important sql schema definitions:

 CREATE UNIQUE INDEX UNIQ_B4905AC83CDDA96E ON t_customer (customer_no); CREATE INDEX IDX_BB041B3B3CDDA96E ON t_myuser (customer_no); ALTER TABLE t_myuser ADD CONSTRAINT FK_BB041B3B3CDDA96E FOREIGN KEY (customer_no) REFERENCES t_customer (customer_no) NOT DEFERRABLE INITIALLY IMMEDIATE; 

So there is definitely an index for customer_no

// update: I am correcting the contents of inversedBy and mappedBy, but this is not a problem.

(1): http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/association-mapping.html#one-to-many-bidirectional

+4
source share
1 answer

@ m2mdas:
Yes, you are right, I thought it was possible because JPA (which affects the doctrine) has this function . The referencedColumnName attribute is only for the case when your property does not match the table column.

Be that as it may, I found a solution by fixing BasicEntityPersister.php, see the gist on github here: https://gist.github.com/3800132

the solution is to add the name / value of the property / field for the collation column. This information already exists, but is not related to the right place. It should be added to $ newValId as follows:

 $fieldName = $targetClass->getFieldName($targetColumn); $newValId[$fieldName] = $targetClass->getFieldValue($newVal, $fieldName); 

It only works for ManyToOne links. ManyToMany does not work.
For ManyToOne, I am testing it with existing objects. You can also check this:

change doctrine annotation in tests/Doctrine/Tests/Models/Legacy/LegacyArticle.php
from

 @JoinColumn(name="iUserId", referencedColumnName="iUserId") 

to

 @JoinColumn(name="username", referencedColumnName="sUsername") 
+1
source

Source: https://habr.com/ru/post/1435579/


All Articles