没有在CakePHP应用程序中获取关联所需的所有数据

没有在CakePHP应用程序中获取关联所需的所有数据,php,cakephp,Php,Cakephp,我在CakePHP中构建了一个应用程序,用户可以与其他用户成为朋友。一个用户有一个配置文件,友谊在朋友表中的用户ID之间链接 在my FriendsController中,我传递一个用户名,然后使用以下方法为用户获取好友:注意,此方法在我的用户模型中,类似:$this->User->getFriends$username;在我的朋友控制 我的用户模型: 类用户扩展AppModel { public$name='User' public $hasOne = 'Profile'; public $

我在CakePHP中构建了一个应用程序,用户可以与其他用户成为朋友。一个用户有一个配置文件,友谊在朋友表中的用户ID之间链接

在my FriendsController中,我传递一个用户名,然后使用以下方法为用户获取好友:注意,此方法在我的用户模型中,类似:$this->User->getFriends$username;在我的朋友控制

我的用户模型:

类用户扩展AppModel { public$name='User'

public $hasOne = 'Profile';

public $hasMany = array(
    'UserFrom'=>array(
        'className'=>'Friend',
        'foreignKey'=>'user_from'
    ),
    'UserTo'=>array(
        'className'=>'Friend',
        'foreignKey'=>'user_to'
    )
);
}

和我的个人资料模型:

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

    public $belongsTo = 'User';
}
朋友模式:

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

    public $belongsTo = array(
        'UserFrom'=>array(
            'className'=>'User',
            'foreignKey'=>'user_from'
        ),
        'UserTo'=>array(
            'className'=>'User',
            'foreignKey'=>'user_to'
        )
    );
}
因此,我认为:

<?php foreach ($friends as $friend) : ?>

        <?php echo $friend['UserTo']['firstname']; ?>

    <?php endforeach; ?>
所以这显然是一个链接用户的问题,我也需要包含这些配置文件。。。但我如何做到这一点,就好像我在UserTo中放置了一个contain,UserFrom会抛出一个错误,说它们没有关联

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

    public $hasOne = 'Profile';
    public $belongsTo = array(
      'Friend'=>array(
        'foreignKey' => 'user_to'
      )
    );
}

class Profile extends AppModel {
    public $name = 'Profile';
    public $belongsTo = 'User';
}

class Friend extends AppModel {
    public $name = 'Friend';
    public $hasOne = 'User';
}
现在可以通过以下方式获取用户朋友:

$this->Friend->find("all", array(
  'conditions'=>array(
    'Friend.user_from'=>$user_id,
  )
  'contain'=>array(
    'User'=>array(
      'contain'=>'Profile'
    )
  )
));

不完全理解。你能把我应该拥有的每一个模型贴出来吗。。。谢谢。嘿,好吧,我稍微修改了我的文章,请阅读更多关于HABTM实现的内容,我还根据您的代码编写了一些示例。希望对您有所帮助。+1如果您想要自定义好友模型,即状态字段,您应该使用带有“with”键的HABTM。那么如何获取好友?或者只是请求,就像你已经将关系和查询组合在一起一样…尝试过这样做,但根本不起作用,只是抛出了很多sql错误,说事情没有关联等等。我的代码更接近了,只是没有通过拉朋友档案!
class User extends AppModel {
    public $name = 'User';

    public $hasOne = 'Profile';
    public $belongsTo = array(
      'Friend'=>array(
        'foreignKey' => 'user_to'
      )
    );
}

class Profile extends AppModel {
    public $name = 'Profile';
    public $belongsTo = 'User';
}

class Friend extends AppModel {
    public $name = 'Friend';
    public $hasOne = 'User';
}
$this->Friend->find("all", array(
  'conditions'=>array(
    'Friend.user_from'=>$user_id,
  )
  'contain'=>array(
    'User'=>array(
      'contain'=>'Profile'
    )
  )
));