Table associations - Multiple relations to the same model in CakePHP 4.2.4

Hello everybody, I am pretty sure that my problem has simple and fast solution but I can’t find it.

I have two tables, Countries table and Dir117s table, i.e:

table

How to write my index.php template for the Dir117s table so that I could see country name instead of country id?

In fact, a Country belongs to many Dir117s and each Dir117s consignee_country_id and consignor_country_id has a Country. Can I defin associations like as follows:

Dir117sTable.php as:
$this->belongsTo(‘Countries’, [
‘foreignKey’ => ‘consignor_country_id’,
‘foreignKey’ => ‘consignee_country_id’,
]);

and

CountriesTable.php

$this->hasMany(‘Dir117s’, [
‘foreignKey’ => ‘consignee_country_id’,
‘foreignKey’ => ‘consignor_country_id’,
]);

?

Unfortunately I was not able to apply solution fro cakephp 2.0 found here: Associations: Linking Models Together - 2.x to my cakephp 4.0 site.

Thank you for any hint or help.

You can distinguish between the two by setting a different alias name than the table name:

Dir117sTable.php

$this->belongsTo('ConsigneeCountries', [
    'foreignKey' => 'consignee_country_id',
    'className' => 'Countries'
]);
$this->belongsTo('ConsignorCountries', [
    'foreignKey' => 'consignor_country_id',
    'className' => 'Countries'
]);

CountriesTable.php

$this->hasMany('ConsigneeDir117s', [
    'foreignKey' => 'consignee_country_id',
    'className' => 'Dir117s'
]);
$this->hasMany('ConsignorDir117s', [
    'foreignKey' => 'consignor_country_id',
    'className' => 'Dir117s'
]);

You might also be able to combine them with finders, but I am not exactly sure how those would work.

Thank you so much, @larsgw ! That is exactly what I needed. Everything works as it should. If anybody had similar problem, the solution contiue as follows.

Based on @larsgw solution, I modified my Dir117sController.php as follows:

Index view template was then modified as follows:

And the result looks like this:

:+1:

1 Like