Doctrine many to one relation with no additional key
I've made some projects with many-to-one/many relations, foreign keys etc
in doctrine and they all worked well. At least as long as I could join
them by id and some other index.
This time I have a table with invoices and another table with company
addresses etc. A simplified Invoice.orm.yml looks like this:
uniqueConstraints:
event_user_idx:
columns: seller,number
manyToOne:
companyData:
targetEntity: CompanyData
joinColumns:
seller:
referencedColumnName: vatNo
fields:
id:
type: integer
id: true
generator:
strategy: AUTO
seller:
type: string
length: '16'
number:
type: string
length: '32'
while CompanyData.orm.yml looks like this:
indexes:
nip:
columns: [ nip ]
fields:
id:
type: integer
id: true
generator:
strategy: AUTO
name:
type: string
length: '128'
vatNo:
type: string
length: '16'
Usually I would just add a new field to Invoices, like 'company_id' and
everything would (most likely) work well. However, as vatNo is a unique
number (as there are no two companies with the same vat number) I don't
want to create necessary artificial keys. So I've made a unidirectional
many-to-one mapping as above. Everything works well when I get data from
the database. I can make a query like this:
SELECT f, c
FROM MyBundle:Invoices i
LEFT JOIN i.companyData c
WHERE f.seller = :seller
and get all the invoices with companies related to it. However, there's a
problem with adding new entities to the database - after adding a foreign
key, I can no longer change the 'seller' field. I tried
$invoice->setSeller('some string')
and
$invoice->setCompanyData($companyData) //some CompanyData object fetched
from DB
it is set to null anyway. While 'seller' is not nullable, I get an exception.
I've tried to change the mapping to:
manyToOne:
companyData:
targetEntity: CompanyData
joinColumns:
seller_other_column:
referencedColumnName: vatNo
and then the query was successful, but the seller_other_column was set to
null anyway. Another strange thing is that when I call
echo $invoice->getSeller();
print_r($invoice->getCompanyData());
$em->persist($invoice);
$em->flush();
it displays the proper data (vat number and CompanyData object), but these
data are nulled anyway, before saving to the database.
Do you have any idea what's wrong?
No comments:
Post a Comment