来自UsersTable
的{{1}}和autoFields
只有2个字段,名为PrimaryBankAccounts
使用查询查询器
版本:Cake 3.2.4
Inside UsersTable.php
$this->hasOne('PrimaryBankAccounts', [
'foreignKey' => 'user_id',
'conditions' => ['PrimaryBankAccounts.primary' => true],
'className' => 'HrBankDetails'
]);
// get user and primary bank details
$usersTable = TableRegistry::get('Users');
$userAndPrimaryBankAccount = $usersTable->find()
->select(['id', 'name'])
->where(['Users.id' => $user_id])
->contain(['PrimaryBankAccounts'])
->autoFields(true)
->first();
本节的最后一段http://book.cakephp.org/3.0/en/orm/query-builder.html#passing-conditions-to-contain
我引用:
或者,如果您有多个关联,则可以使用 autoFields():
// Select id & title from articles, but all fields off of Users, Comments // and Tags. $query->select(['id', 'title']) ->contain(['Comments', 'Tags']) ->autoFields(true) ->contain(['Users' => function($q) { return $q->autoFields(true); }]);
{
"id": 8,
"name": "Calvin Wa",
"email": "calvin@wa.com",
"created": "2015-04-20T09:10:09+0800",
"modified": "2015-04-20T09:10:09+0800",
"group_id": 2,
"phone": null,
"mobile": null,
"address": null,
"comments": null,
"forgot_password_token": null,
"primary_bank_account": {
"id": 1,
"name": "UOB for Calvin",
"user_id": 8,
"bank_name": "UOB",
"account_type": "",
"account_number": "123",
"currency": "USD",
"primary": true,
"created": null,
"modified": null
}
}
{
"id": 8,
"name": "Calvin Wa",
"primary_bank_account": {
"id": 1,
"name": "UOB for Calvin",
"user_id": 8,
"bank_name": "UOB",
"account_type": "",
"account_number": "123",
"currency": "USD",
"primary": true,
"created": null,
"modified": null
}
}