I'm working on an application which has data imported from a foreign (and wholly unchangeable) source. I'll simplify some of the tables to explain the problem. Below are the tables with their primary keys.
invoices (doc_number, date_printed, batch_number)
headers (doc_number, date_printed, batch_number)
deliveries (doc_number, date_printed, batch_number)
transactions (doc_number, date_printed, batch_number, line_number)
messages (doc_number, date_printed, batch_number, line_number)
So you can see that Invoices, Headers and Deliveries have One-to-One relationships. Invoices-to-Transactions and Invoices-to-Messages are One-to-Many.
In importing these tables to my own database, I've changed the existing primary key to be a unique key and added an auto_incrementing field (id) on each table.
Now the problem is setting up the relationships in Cake, since it doesn't really handle composite keys at all. I've been able to get the One-to-One relationships working like this:
class Invoice extends AppModel {
public $name = "Invoice"
, $hasOne = array(
"Header" => array(
'foreignKey' => false,
'conditions' => array(
"Invoice.doc_number = Header.doc_number",
"Invoice.date_printed = Header.date_printed",
"Invoice.batch_number = Header.batch_number"
)
)
)
;
}
And this works, because the one-to-one relationships are queried in one go with a big LEFT JOIN. Trying the same method with a one-to-many relationship (eg, with Invoices and Transactions) dies, because Cake does two queries: the first to find all the matching Invoices, and then the second to find all the Transactions with a corresponding foreign key which matches the results from the first query: (here's the simplified query it's trying to run)
SELECT `Transaction`.* FROM `transactions` AS `Transaction`
WHERE `Invoice`.`doc_number` = `Transaction`.`doc_number`
AND `Invoice`.`date_printed` = `Transaction`.`date_printed`
AND `Invoice`.`batch_number` = `Transaction`.`batch_number`
You can see, it's not joining onto invoices so the query dies.
Any ideas about how I can make this work?