CakePHP:获取登录用户的关联对象

CakePHP:获取登录用户的关联对象,php,cakephp,cakephp-model,Php,Cakephp,Cakephp Model,我尝试向当前登录的用户接收关联模型的数据。 这是我当前的用户模型: class User extends AppModel { public $name = 'User'; public $hasMany = array( 'Website' => array( 'className' => 'Website', 'foreignKey' => 'user_id' ) )

我尝试向当前登录的用户接收关联模型的数据。 这是我当前的用户模型:

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

    public $hasMany = array(
        'Website' => array(
            'className'  => 'Website',
            'foreignKey' => 'user_id'
        )
    );
}
class Website extends AppModel {
    public $name = 'Website';
    public $belongsTo = array(
        'User' => array(
            'classname' => 'User',
            'foreignKey' => 'user_id'
        )
    );
}
这是与用户模型关联的网站模型:

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

    public $hasMany = array(
        'Website' => array(
            'className'  => 'Website',
            'foreignKey' => 'user_id'
        )
    );
}
class Website extends AppModel {
    public $name = 'Website';
    public $belongsTo = array(
        'User' => array(
            'classname' => 'User',
            'foreignKey' => 'user_id'
        )
    );
}
当我尝试获取登录用户的网站时,我不想在DB请求的条件下以静态方式设置网站的用户id。因此,我尝试使用关联:

public function beforeFilter() {
    parent::beforeFilter();
    $this->Website->User->id = $this->Auth->user('id');
    // OR
    $this->Website->User->set($this->Auth->user());
}

public function index() {
    $this->set('websites', $this->Website->find('all'));
}
但它会返回所有网站,而不是仅返回具有正确用户id的网站

有没有办法按照我的建议去做?如果是,我做错了什么

非常感谢

如果使用Model->find('all')将检索该模型的所有记录

使用您的belongTo关系,当您检索用户(使用find->)时,Cake将检索同一集合中的网站。根据您处理身份验证的方式,该数据可能是自用户会话开始以来的数据。

如果使用Model->find('all')将检索该模型的所有记录


使用您的belongTo关系,当您检索用户(使用find->)时,Cake将检索同一集合中的网站。根据您处理身份验证的方式,这些数据可能从用户会话开始就存在了

这似乎是一个很好的解决方案,唯一的问题是Cake现在必须进行2次查询,而不是1次:(当您使用belongsTo关系时,Cake只会自动进行一个查询连接相关表。您能否举例说明如何在控制器中正确使用belongsTo关联,以便Cake只进行一次查询?这似乎是一个很好的解决方案,唯一的问题是Cake现在必须进行两次查询,而不是1次查询:(当您使用belongsTo关系时,Cake只会自动进行一次查询,并连接相关表。请举例说明如何在控制器中正确使用belongsTo关联,以便Cake只进行一次查询?