拉取模型关联时的 Cakephp 控件

Cakephp control when model associations are pulled

我继承了一个使用 Cakephp 2.0 和 Angular 处理各种事情的项目,我正在寻找如何进行连接和模型关联。

我有一个与用户有关联的模型 table 就像这样

App::uses('AppModel', 'Model');

class Booking extends AppModel {

    public $belongsTo = array(
        'Trainer' => array(
            'className' => 'User',
            'foreignKey' => 'to_user'
        ),
        'Participant' => array(
            'className' => 'User',
            'foreignKey' => 'user'
        )
    );

}

这行得通。但是,我担心每次访问预订时总是让所有用户 table 的速度和安全性。大部分数据传递给 angular,然后通过 javascript 显示,我发现有几个地方是程序将模型搜索的结果直接传递给 angular,然后让它处理传播那个数据。我担心,如果我添加这些关联,那么我现在可能会将我的用户 table 传递给 javascript,其中将包含敏感数据。

我想知道是否可以通过使用函数调用在运行时添加关联。例如

App::uses('AppModel', 'Model');

class Booking extends AppModel {

    public function getUserInfo(){
        $this->$belongsTo = array(
            'Trainer' => array(
                'className' => 'User',
                'foreignKey' => 'to_user'
            ),
            'Participant' => array(
                'className' => 'User',
                'foreignKey' => 'user'
            )
        );
    }

}

然后在控制器中使用:

$this->loadModel("Booking");
$this->Booking->getUserInfo();

这样做的目的是让您可以控制相关的 table 是否也被拉动。

您可以Create Associations on the Fly如下,

App::uses('AppModel', 'Model');

class Booking extends AppModel {

    public function getUserInfo(){
    $this->bindModel(
        array('belongsTo' => array(
                'Trainer' => array(
                    'className' => 'User',
                'foreignKey' => 'to_user')),
            'Participant'=> array(
                'className' => 'User',
                    'foreignKey' => 'user' ) )
            );
    return $this->find('all');

    }
}