Saving parent/child header/line using Doctrine 1.2
I have a simple parent-child/header-line model in my project. The problem is that its creating a cyclic relation or something, and not letting me save the p开发者_运维技巧arent without the child! Detect relations is switched off!
detect_relations: false
...
BillHeader:
package: Billing
tableName: Bill_Headers
actAs:
SoftDelete: ~
columns:
id:
type: integer(8)
primary: true
notnull: true
autoincrement: true
....
BillLine:
package: Billing
tableName: Bill_Lines
actAs:
SoftDelete: ~
columns:
id:
type: integer(8)
primary: true
notnull: true
autoincrement: true
bill_header_id:
type: integer(8)
notnull: true
relations:
Bill_Header:
class: BillHeader
local: bill_header_id
foreign: id
foreignAlias: Bill_Lines
type: one
when I save the parent first:
$billHeader->save();
gives error: SQLSTATE[HY000]: General error: 1452 Cannot add or update a child row: a foreign key constraint fails (sokidb
.bill_headers
, CONSTRAINTBill_Headers_id_Bill_Lines_bill_header_id
FOREIGN KEY (id
) REFERENCESbill_lines
(bill_header_id
))when I do
$billHeader->Bill_Lines[] = $billLine;
gives the error: Add is not supported for BillLineThe line won't save without the parent, so I can't even do
$billHeader->link('Bill_Lines', $billLines);
$billHeader->Bill_Lines = $billLines;
gives the error Couldn't call Doctrine_Core::set(), second argument should be an instance of Doctrine_Collection when setting one-to-many references.If I drop the relationship, do a
$billHeader->save();
, then$billHeader->id
returns empty. So thats not working either!
I wonder if there is a 6th way of doing it??? :(
I'm tired of thinking on this problem, there seems to be no solution. Almost 3 days on this and now clue! its getting me suicidal! why this behaviour? Will it help if the table is MyIsam instead of InnoDB?
Any help on this is much appreciated! Thanks in advance.
Something is wrong with your schema. The constraint:
CONSTRAINT Bill_Headers_id_Bill_Lines_bill_header_id FOREIGN KEY (id) REFERENCES bill_lines (bill_header_id))
Should not exist. The id of BillHeader should not be a foreign key of BillLine. Instead, there should be a constraint from BillLine to BillHeader, something like:
CONSTRAINT `Bill_Lines_header_id_Bill_Header_id` FOREIGN KEY (`bill_header_id`) REFERENCES `Bill_Header` (`id`)
Do you have additional relations defined on BillHeader that may be adding that constraint? Regardless, the key here is to play with your schema until the constraint is going in the right direction.
I solved it after much introspection. One of the attributes declared was marked PRIMARY. Don't know why this result, but this was the problem!
精彩评论