0

我正在使用 CakePHP 3.4

我正在检索用户的信息,例如

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

在这里,UserAddressesuser_id列和state_id列,States表有country_id列。

如果表中没有关联的 user_address,那么 即使在不存在记录的情况下,我也会在从作品中正常record not found移除时给出错误States.CountriescontainUserAddresses

编辑 2:关系

用户表.php

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

用户地址表.php

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

状态表.php

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

国家表.php

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

2 回答 2

3

正如 Kilian Schuster 所说,您的条件适用于Countries. 我改了,试试下面的代码:

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

编辑:如果没有与得到的用户相关的地址,record not found错误可能是由Inner join国家模型的类型引起的。Left如果关系是可选的,则将连接类型更改为。

于 2017-04-19T13:28:05.773 回答
0

使用这种语法,您实际上是在尝试将条件应用于“Countries”模型,而不是“UserAddresses”模型。

于 2017-04-19T12:31:32.357 回答