0

我的 CakePHP 应用程序有以下表格,允许用户之间建立友谊:

**Users**
id
username
password

**Profiles**
id
firstname
lastname
user_id

**Friends**
id
user_id_to
user_id_from
status

所以基本上一个用户有一个个人资料,一个用户可以和另一个用户成为朋友,这被记录在称为朋友的数据库表中,简单的状态是确认或不使用 0 或 1(它是一个 int)。所以朋友是两个用户之间的加入。

我正在尝试为用户列出朋友,例如,如果我得到如下网址:

/people/cameron/friends它将列出用户 Cameron 的朋友。

但是,我正在努力使用 find 语句来传递用户并找到它们(注意我包含个人资料数据),然后列出与该用户相关的朋友。任何人都可以帮忙吗?

这些是朋友、用户和个人资料模型:

class Friend extends AppModel
{
    public $name = 'Friend';

    public $belongsTo = array('User');

    public $actsAs = array('Containable');

}

用户.php

   class User extends AppModel
    {
        public $name = 'User';

    public $hasOne = 'Profile';

    public $hasMany = array(
        'Post',
        'Answer',
        'Friend' => array(
            'foreignKey' => 'user_id_to'
        )
    );

public $belongsTo = array(
        'Friend' => array(
            'foreignKey' => 'user_id_from'
        )
    );

    public $actsAs = array('Containable');

        public function getFriends($username)
        {
        return $this->find('all',
        array('conditions' => array('User.username' => $username, 'Friend.status'=>1),
            'contain' => array('Friend' => array('User'))
        ));
        }
    }

配置文件.php

class Profile extends AppModel
{
    public $name = 'Profile';

    public $belongsTo = 'User';

    public $actsAs = array('Containable');
}

这是我为用户显示朋友列表的方法:

public function index( $username )
{   
    $friends = $this->User->getFriends($username);

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

我目前收到此错误:

Error: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'User.user_id_from' in 'on clause'
SQL Query: SELECT `User`.`id`, `User`.`username`, `User`.`password`, `User`.`email`, `User`.`status`, `User`.`code`, `User`.`lastlogin`, `Friend`.`id`, `Friend`.`user_id_from`, `Friend`.`user_id_to`, `Friend`.`datetime`, `Friend`.`status` FROM `db52704_favorr`.`users` AS `User` LEFT JOIN `db52704_favorr`.`friends` AS `Friend` ON (`User`.`user_id_from` = `Friend`.`id`) WHERE `User`.`username` = 'cameron' AND `Friend`.`status` = 1

看起来应用程序认为外键在 User 表中而不是在朋友表中,即使它们在 Friend 关联中调用...任何想法是什么问题?

4

2 回答 2

0

在构造连接查询时,Cake 似乎对那些 foreignKey 分配感到困惑。

您可以尝试用以下内容替换每个关系以强制执行正确的连接语句:

public $hasMany = array(
    'Friend' => array(
        'foreignKey' => null,
        'conditions' => array('Friend.user_id_to = User.id')
    )
);

public $belongsTo = array(
    'Friend' => array(
        'foreignKey' => null,
        'conditions' => array('Friend.user_id_from = User.id')
    )
);
于 2012-04-09T22:17:59.813 回答
0

每当您为 $belongsTo 指定外键时,请记住您指定的名称是当前表中的字段名称,而不是其他表中的字段名称。

因此,例如,您对 $belongsTo 的引用'foreignKey' => 'user_id_to'应该在Friends 模型中,而不是在 Users 模型中。

Re-read Cake's docs, as it does get confusing (even after years of Cake apps, I still need to refresh when I start a new project): http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html

于 2012-04-09T22:30:52.130 回答