cakephp: targetForeignKey in belongsToMany doesn't have effect, defaults to target model name
Description
Still not sure this is actually a bug but can’t get any help anywhere. this association
$this->belongsToMany('Bonus', [
'foreignKey' => 'product_id',
'joinTable' => 'products_bonuses',
'className' => 'Products',
'targetForeignKey' => 'bonus_id',
]);
generates this query
SELECT ProductsBonuses.id AS Bonus_CJoin__id,
ProductsBonuses.product_id AS Bonus_CJoin__product_id,
ProductsBonuses.bonus_id AS Bonus_CJoin__bonus_id,
Bonus.id AS Bonus__id
FROM products Bonus
INNER JOIN products_bonuses ProductsBonuses ON Bonus.id = ProductsBonuses.product_id
WHERE ProductsBonuses.product_id in (57, 58);
which gives me wrong results.
When I correct it to use bonus_id instead of product_id in INNER JOIN I get correct results.
When I remove targetForeignKey it has no effect.
When I give it invalid value it also has no effect.
According to documentation
targetForeignKey: The name of the foreign key that references the target model found on the join model [...] The default value for this key is the underscored, singular name of the target model, suffixed with ‘_id’.
it feels like it always defaults to class name (instead of alias) and in my case I’m joining the same table but under different alias.
CakePHP Version
4.3.6
PHP Version
7.4
About this issue
- Original URL
- State: closed
- Created 2 years ago
- Comments: 18 (10 by maintainers)
Sure.
Now all of your aliases are unique and shouldn’t conflict.
Hei! Finally reproduced
.sqlbelowcake bake model Productscake bake model ProductsLinkedProductsLinkedProductsassociation toProductsTable:cake bake command test):Result will be:
But if i remove association for
ProductsLinkedProductsfromProductsTablethen query returns correctlinked_productsentries:The problem is that query ignoring
targetForeignKeyoption if there are already relation for specifiedjoinTablewhich seems wrong. One table should have ability to have two exact relation classes but joined from different fields.By the way - this problem doesn’t exists in cake2.
Thanks!
Here the
.sql