在 CakePHP 3 的包含模型上找不到记录
record not found on contain model in CakePHP 3
我正在使用 CakePHP 3.4
我正在检索像
这样的用户的信息
$user = $this->Users->get($id, [
'contain' => [
'UserAddresses.States.Countries' => ['conditions' => [
'UserAddresses.deleted' => false]],
],
]);
此处,UserAddresses
有 user_id
列和 state_id
列,States
table 有 country_id
列。
如果table中没有关联的user_address,那么我给
record not found
错误
从 contain
中删除 States.Countries
时工作正常,即使 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'
]);
使用此语法,您实际上是在尝试将条件应用于 "Countries" 模型,而不是 "UserAddresses" 模型。
正如 Kilian Schuster 所说,您的条件适用于 Countries
。我改变了它,试试下面的代码:
$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.
我正在使用 CakePHP 3.4
我正在检索像
这样的用户的信息$user = $this->Users->get($id, [
'contain' => [
'UserAddresses.States.Countries' => ['conditions' => [
'UserAddresses.deleted' => false]],
],
]);
此处,UserAddresses
有 user_id
列和 state_id
列,States
table 有 country_id
列。
如果table中没有关联的user_address,那么我给
record not found
错误
从 contain
中删除 States.Countries
时工作正常,即使 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'
]);
使用此语法,您实际上是在尝试将条件应用于 "Countries" 模型,而不是 "UserAddresses" 模型。
正如 Kilian Schuster 所说,您的条件适用于 Countries
。我改变了它,试试下面的代码:
$user = $this->Users->get($id, [
'contain' => [
'UserAddresses' => [
'conditions' => [
'UserAddresses.deleted' => false
]
],
'UserAddresses.States.Countries'
]
]);
Edit: The
record not found
error could be caused by theInner join
type for Countries in States model if there is no address related to the got user. Change the join type toLeft
if the relationship is optional.