CakePHP 3:检索深层关联

时间:2015-11-14 23:36:55

标签: cakephp-3.0

我的模特有

Conversations - hasMany - Messages

Conversations - hasMany - ConversationsRecipients

ConversationsRecipients - areTo - UsersApplicants(取决于字段recipient_type设置的标记。如果recipient_type为A则表示申请人)< / p>

因此,当我尝试检索特定申请人的对话时,我使用以下代码

$conversationsTable = TableRegistry::get('Conversations');
        $conversations = $conversationsTable->find()
            ->join([
                'ConversationsRecipients' => [
                    'table' => 'conversations_recipients',
                    'type' => 'inner',
                    'conditions' => ['recipient_id' => $id, 'recipient_type' => 'A']
                ]
            ])
            ->contain([
                'Messages.Users' => function ($q) {
                    return $q
                        ->select(['Users.username'])
                        ->contain(['UsersProfiles']);
                },
                'Messages.Applicants' => function($q) {
                    return $q
                        ->select(['Applicants.firstname', 'Applicants.lastname']);
                }
            ])
            ->all();
        return $conversations;

这很好 - 除了一部分 - 但它不能检索深度包含的模型 - UsersProfiles。我错过了什么吗?

1 个答案:

答案 0 :(得分:1)

试试这个:

return $q
    ->select(['Users.username'])
    ->autoFields(true)
    ->contain(['UsersProfiles']);

如果在查询中包含一个select,那么Cake将包含 all ,除非您包含autoFields调用。