LoginSignup
2
2

More than 5 years have passed since last update.

CakePHP2で、アソシエーションを動的に変更する

Posted at

動的にというか、コントローラ側で一時的に条件を変えてアソシエートしたい、というケース。
例えばOfficeモデルに複数のUserがいる、という場合で、OfficeモデルにhasManyでUserが設定されている、というような場合、bakeを使って生成すると、

Office.php
    public $hasMany = array(
        'User' => array(
            'className' => 'User',
            'foreignKey' => 'office_id',
            'dependent' => false,
            'conditions' => '',
            'fields' => '',
            'order' => '',
            'limit' => '',
            'offset' => '',
            'exclusive' => '',
            'finderQuery' => '',
            'counterQuery' => ''
        )
    );

というようになっているはずである。特に条件は指定していないので、同じoffice_idを持つUserのうち最初のuserが取り出される。
これをある時だけ、Userのstatusが1のものだけを引っ張りたい、という時どうすればいいか?
コントローラの使いたい場所でbindModelを使えば良い。そこにアソシエーションの設定を好きなように書けば良い。

OfficesController.php
    $this->Office->bindModel(
        array('hasMany' => array(
            'User' => array(
                'className' => 'User',
                'foreignKey' => 'office_id',
                'dependent' => false,
                'conditions' => array('User.status' => '1'),
                'fields' => '',
                'order' => '',
                'limit' => '',
                'offset' => '',
                'exclusive' => '',
                'finderQuery' => '',
                'counterQuery' => ''
            ))
        )
    );
    $options = array('conditions' => array('Office.' . $this->Office->primaryKey => $id));
    $this->request->data = $this->Office->find('first', $options);
2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2