如何使用HABTM查找数据

时间:2014-04-09 22:13:50

标签: cakephp cakephp-2.0 has-and-belongs-to-many

User HABTM到Solicitation SocilitationUser模型。

当我debug($this->User->find('all'));时,我得到了这个数组

array(
(int) 0 => array(
    'User' => array(
        'password' => '*****',
        'id' => '1',
        'username' => 'advogado',
        'email' => 'igor.cesar@sotreq.com.br',
        'nivel' => 'advogado',
        'nome' => 'Bruno',
        'superior' => '0',
        'sector_id' => '2',
        'aprovador' => '1'
    ),
    'SolicitationUser' => array(
        (int) 0 => array(
            'id' => '9',
            'solicitation_id' => '72',
            'user_id' => '1',
            'funcao' => ''Advogado''
        ),
        (int) 1 => array(
            'id' => '11',
            'solicitation_id' => '73',
            'user_id' => '1',
            'funcao' => ''Advogado''
        ),
           ...... 

我怎样才能获得所有Solicitations active = 1user.id = 1 ??

2 个答案:

答案 0 :(得分:0)

如果用户的字段处于活动状态(根据您发布的结果,我无法在User和SolicitationUser中看到该字段处于活动状态)

  $conditions = "User.active=1 AND SolicitationUser.user_id=1"; //if the active belongs to SolicitationUser model just modify it to SolicitationUser.active
  $solicitations = $this->Solicitation->find('all', compact('conditions'));

答案 1 :(得分:0)

我觉得通过HABTM模型很有效:

$this->SolicitationUser->find('all',array(
    'conditions'=>array('SolicitationUser.user_id'=>1,'Solicitation.active'=>1)
);