在CakePHP 3.x中拥有关联表的所有自动对象时,选择查询中主表的字段?

时间:2016-04-04 12:00:49

标签: cakephp cakephp-3.0

我想要什么

来自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
    }
}

0 个答案:

没有答案