CakePHP:使用bindModel向后追踪3个模型?

时间:2012-01-11 20:58:14

标签: mysql cakephp cakephp-1.2

我有以下型号:

-> = 1:很多,<-> =很多:很多

用户 <->产品 -> MessageList中 <->消息

此查询的目标是找到与登录对应的所有消息。我还过滤掉已读取的消息(我在先前的查找中找到消息ID并将其存储在$messageIdsReadByPerson中)。

这是我的尝试:

        // only grab messages belonging to this user
        $this->Message->unbindModel(array('hasAndBelongsToMany'=>array('MessageListsMessage')));

        $this->Message->bindModel( array(
            'hasOne' => array(
                'MessageListsMessage' => array(
                    'className' => 'MessageListsMessage',
                    'foreignKey' => false,
                    'type' => 'INNER',
                    'conditions' => array(
                        'MessageListsMessage.message_id = Message.id'
                    )
                ),
                'MessageList' => array(
                    'className' => 'MessageList',
                    'foreignKey' => false,
                    'type' => 'INNER',
                    'conditions' => array(
                        'MessageList.id = MessageListsMessage.message_list_id'
                    )
                ),
                'Product' => array(
                    'className' => 'Product',
                    'foreignKey' => false,
                    'type' => 'INNER',
                    'conditions' => array(
                        'Product.id = MessageList.product_id'
                    )
                ),
                'ProductsUser' => array(
                    'className' => 'ProductsUser',
                    'foreignKey' => false,
                    'type' => 'INNER',
                    'conditions' => array(
                        'ProductsUser.product_id = Product.id'
                    )
                ),
                'User' => array(
                    'className' => 'User',
                    'foreignKey' => false,
                    'conditions' => array(
                        'User.id = ProductsUser.user_id',
                        'User.id' => $this->Auth->user('id')
                    )
                )
            )
        ));
        $messages = $this->Message->find('all', array(
            'recursive' => -1
        ));
        $this->set('messages', $messages);

但这只会提供此查询:

SELECT `Message`.`id`, `Message`.`text`, `Message`.`url` FROM `messages` AS `Message` WHERE 1 = 1

如何使用bindModel(或者我不知道的一些更简单的方法)来正确完成,虽然joins显然不是可行的方法。)

编辑: 这也不起作用:

function index() {
    // only grab messages belonging to this user
    $messages = $this->Message->find('all', array(
        'contain' => array(
            'MessageList' => array(
                'Product' => array(
                    'User.id = ' . $this->Auth->user('id')
                )
            )
        )
    ));
    $this->set('messages', $messages);
}

1 个答案:

答案 0 :(得分:1)

我认为同样的答案适用于我刚才给出的答案: How to get only products with images in CakePhp

可包含或递归更高