0

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'
]);
Anuj TBE
  • 9,198
  • 27
  • 136
  • 285

2 Answers2

3

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.

Rayann Nayran
  • 1,135
  • 7
  • 15
  • Update your question and tell which are the relationships between the models, depending on it, you should use matching() or innerJoinWith(). – Rayann Nayran Apr 19 '17 at 16:29
  • I think there is a State that has no country related, and because the Inner join type you are getting the record not found error. – Rayann Nayran Apr 19 '17 at 17:29
  • There is only one state record and one country record in the table and state record is associated with country. Yes, there is not associated user_address in the table whose record I'm searching for. But It works even when there is no associated `user_address` record when removed `States.Countries` but throwing error when `States.Country` is present – Anuj TBE Apr 19 '17 at 17:32
  • Change the join type to left just to see if it works. – Rayann Nayran Apr 19 '17 at 17:56
  • whose join type ? – Anuj TBE Apr 19 '17 at 17:57
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/142107/discussion-between-rayann-nayran-and-anuj-tbe). – Rayann Nayran Apr 19 '17 at 17:57
0

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