php - hasAndBelongsToMany 不提取关联外键的数据

标签 php cakephp

在我的 CakePHP 应用程序中,我的用户可以与其他用户成为 friend 。

这是通过一个users表和一个friends_users表来完成的,该表具有以下列:id、user_id、friend_id、status关系。

因此,如果用户 ID 1 是用户 ID 2 的好友,则 user_id 列中将包含 1,friend_id 列中将包含 2

用户的模型如下所示:

public $hasAndBelongsToMany = array(
        'Friend'=>array(
            'className'              => 'User',
            'joinTable'              => 'friends_users',
            'foreignKey'             => 'user_id',
            'associationForeignKey'  => 'friend_id'
        )
    );

查看用户 1 时,它工作正常并将用户 2 显示为好友。但是,当查看用户 2 时,它不会将用户 1 显示为好友...因此,反向查看时,数据并未填满!

这是我用来列出用户好友的方法:

$user = $this->User->find('first', array( 
                    'conditions' => array('User.id' => $this->Auth->user('id')),
                    'contain'=>'Profile'
                ));

        $friends = $this->User->find('first', 
            array(
                'conditions'=>array(
                   'User.id'=>$user['User']['id']
                ),
                'contain'=>array(
                    'Profile',
                    'Friend'=>array(
                        'Profile',
                        'conditions'=>array(
                            'FriendsUser.status'=>1
                        )
                    )
                )
            )
        );

        $this->set('friends', $friends);

有什么想法为什么会发生这种情况吗?我已经浏览了文档,但对我来说一切似乎都很好。

理想情况下,我想修复我的代码,而不是被指向其他资源!

页面查询:http://pastebin.com/zQnBVM2X

最佳答案

当您为用户 #6 检索好友时,您将获得好友 #8。当您检索用户 #8 的 friend 时,您应该不会收到任何结果,因为您的 friends_users 表中没有用户 #8 的记录。因此,您需要在 friends_users 表中插入其他数据 (user_id = 8,friend_id = 6),或者需要创建 Friend 模型 (不使用表)并通过 Friend 检索用户。这是心理体操 - 你需要意识到用户是 friend , friend 就是用户。

        $friends = $this->User->Friend->find('first', 
            array(
                'conditions'=>array(
                   'Friend.id'=>$id // user id whose friends you need to find
                ),
                'contain'=>array(
                    'Profile',
                    'User'=>array( // here you will get friends
                        'Profile',
                        'conditions'=>array(
                            'FriendsUser.status'=>1
                        )
                    )
                )
            )
        );

关于php - hasAndBelongsToMany 不提取关联外键的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12611259/

相关文章:

cakephp - Controller 中获取当前 url 的方法

php - 从 CakePHP 中的相关项目项获取项目的总计

sql - 如何在 Controller 中看到 CakePHP 的 SQL 转储?

mysql - CakePHP 显示作者不在作者表中的所有书籍

php - 我如何在 CakePHP 中使用缓存?

php - 在 Imagemagick for linux 中,如何对目录进行批量转换

php - 有一个数字 1 出现在我的 HTML 页面上,即使我没有把它放在那里

php - 调用创建付款时出现 MALFORMED_REQUEST

php - ECK Drupal 模块 + Commerce Marketplace 实体错误

php - php 中单独线程上的电子邮件