How to implement a belongstTo with cakePhp 4 with conditions and different data types

127 Views Asked by At

My design has two models ModelOne and ModelTwo. In ModelOne there is an integer field which passes as a foreign key to ModelTwo as a varchar.

The original implementation from a previous version (cakephp 2) of cake is as follow:

$this->belongsTo('ModelOne')
    ->setProperty('ModelOne')
    ->setClassName('ModelOnes')
    ->setConditions(['ModelOne.field_one::TEXT = ModelTwo.field_one AND ModelOne.field_two = ModelTwo.field_two']);

As you can see the cast is needed because if it is not used a data type mismatch exception is thrown.

When I use it like that an exception is thrown because it seems the function CAST is not properly used. The same happens when I pass to the setCondition method a QueryExpression resulted from using the $query->func()->CAST(...) function provided by ORM.

How can I solve this and specify correctly the belongsTo relation?

Thanks in advance!

I'm trying to configure properly a belongsTo relation in cakephp 4 with two different data types using datatype casting with the SQL function cast or other valid approach.

After edit:

$this->belongsTo('List')->setProperty('List')->setClassName('Lists')->setConditions(['List.code::TEXT = WhiteList.code AND List.list = WhiteList.list']);
0

There are 0 best solutions below