Cakephp HABTM join between plugin and core application
-
27-06-2021 - |
Frage
I'm having real issues doing a HABTM join between a model/table on a plugin and a model/table in my core application.
Basically my core application has a model for Items, and my plugin has a model for Purchases.
One purchase can be of many items.
I've got tables defined, all the tables in my plugin have the prefix itm_ (to denote that they're handling items)
The plugin is called itemServices.
Join table is part of the plugin and is itm_purchases_items
HABTM code is (on Item in Core):
'itemServices.Purchase' => array(
'className' => 'itemServices.Purchase',
'joinTable' => 'itm_purchases_items',
'foreignKey' => 'item_id',
'associationForeignKey' => 'purchase_id',
'unique' => 'keepExisting',
),
and (on Purchases in Plugin):
'Item' => array(
'className' => 'Item',
'joinTable' => 'itm_purchases_items',
'foreignKey' => 'purchase_id',
'associationForeignKey' => 'item_id',
'unique' => 'keepExisting',
)
I'm getting SQL errors because the auto-generated query is trying to use the following notation for one side of the join
`itm_purchases` AS `itemServices`.`Purchase`
which is creating an invalid query.
Any ideas on the correct way of doing this?
The generated SQL is (db names removed)
SELECT `itemServices`.`Purchase`.`id`,
`itemServices`.`Purchase`.`customer_id`,
`itemServices`.`Purchase`.`agreement_number`,
`itemServices`.`Purchase`.`total_value`,
`itemServices`.`Purchase`.`item_count`,
`itemServices`.`Purchase`.`created`,
`itemServices`.`Purchase`.`modified`,
`purchases_items`.`purchase_id`,
`purchases_items`.`item_id`,
`purchases_items`.`created`,
`purchases_items`.`modified`
FROM
`itm_purchases` AS `itemServices`.`Purchase`
JOIN
`itm_purchases_items` AS `purchases_items`
ON
(`purchases_items`.`item_id` = 18 AND `purchases_items`.`purchase_id` = `itemServices`.`Purchase`.`id`)
Lösung
Found the problem,
'itemServices.Purchase' => array(
'className' => 'itemServices.Purchase',
'joinTable' => 'itm_purchases_items',
'foreignKey' => 'item_id',
'associationForeignKey' => 'purchase_id',
'unique' => 'keepExisting',
),
Should actually be:
'Purchase' => array(
'className' => 'itemServices.Purchase',
'joinTable' => 'itm_purchases_items',
'foreignKey' => 'item_id',
'associationForeignKey' => 'purchase_id',
'unique' => 'keepExisting',
),