【问题标题】:CakePHP - unwanted HABTM contained in find using "contain"CakePHP - 使用“包含”查找包含的不需要的 HABTM
【发布时间】:2012-01-23 21:07:10
【问题描述】:

我正在使用 CakePHP 创建一个消息传递系统。在模型方面,

Users HABTM Conversations
Conversations hasMany Messages
Messages belongTo User (the sender)

所以我在用户上运行一个查找条件,包含如下:

$user = $this->Conversation->User->find('first', array(
        'conditions' => array('User.id' => $user_id),
        'contain' => array(
            'Conversation' => array(
                'ConversationsUser',
                'Message' => array(
                    'order' => 'Message.created DESC',
                    'limit' => 1,
                    'User' => array(
                        'Student' => array(
                            'University'
                        ),
                        'Recruiter' => array(
                            'Org'
                        )
                    )
                )
            )
        )
    ));

当我得到结果时,我得到 $user['Conversation']['Message']['User']['Conversation'] - 基本上,HABTM 连接会自动完成 3 级深度,没有办法我来阻止它。我有什么方法可以从查找中删除此信息?

【问题讨论】:

  • 你在哪里设置了可包含行为?如果您没有在 AppModel 中设置(或单独在 each 模型中),我可以想象如果您包含一个不使用 Containable 行为的模型,那么该模型将获取相关数据根据其“递归”设置。 (这是一个猜测,这就是为什么我还没有写它作为答案)

标签: cakephp


【解决方案1】:

解决了。我通过以下方式重组了查找:

$this->Conversation->bindModel(array('hasOne' => array('ConversationsUser')));
$conversations = $this->Conversation->find('all', array(
        'conditions' => array('ConversationsUser.user_id' => $user_id),
        'order' => 'Conversation.modified DESC',
        'contain' => array(
            'ConversationsUser',
            'User' => array(
                'conditions' => array('User.id <> ' . $user_id),
                'ProfilePhoto' => array(
                    'Attachment'
                ),
                'Student' => array(
                    'University'
                ),
                'Recruiter' => array(
                    'Org'
                )
            ),
            'Message' => array(
                'order' => 'Message.created DESC'
            )
        )
    ));

我真的不需要在消息中包含用户。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-11-29
    • 2012-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多