0
votes

I am using CakePHP 3.4

I am retrieving information of user like

$user = $this->Users->get($id, [
    'contain' => [
        'UserAddresses.States.Countries' => ['conditions' => [
               'UserAddresses.deleted' => false]],
    ],
]);

Here, UserAddresses have user_id column and state_id column and States table have country_id column.

If there is no associated user_address in table, then I gives record not found error while removing States.Countries from contain works fine even when record does not exists in UserAddresses

Edit 2 : Relationships

UsersTable.php

$this->hasOne('UserAddresses', [
    'foreignKey' => 'user_id'
]);

UserAddressesTable.php

$this->belongsTo('Users', [
    'foreignKey' => 'user_id',
    'joinType' => 'INNER'
]);
$this->belongsTo('States', [
    'foreignKey' => 'state_id',
    'joinType' => 'INNER'
]);

StatesTable.php

$this->belongsTo('Countries', [
    'foreignKey' => 'country_id',
    'joinType' => 'INNER'
]);
$this->hasMany('UserAddresses', [
    'foreignKey' => 'state_id'
]);

CountriesTable.php

$this->hasMany('States', [
    'foreignKey' => 'country_id'
]);
2

2 Answers

3
votes

As Kilian Schuster said, your condition is being applied to Countries. I changed it, try the code bellow:

$user = $this->Users->get($id, [
    'contain' => [
        'UserAddresses' => [
            'conditions' => [
               'UserAddresses.deleted' => false
            ]
        ],
        'UserAddresses.States.Countries'
    ]
]);

Edit: The record not found error could be caused by the Inner join type for Countries in States model if there is no address related to the got user. Change the join type to Left if the relationship is optional.

0
votes

With this syntax, you are actually trying to apply the conditions to the "Countries" model, and not to the "UserAddresses" model.