2011-11-29 56 views
2

假设我们有3种型号,用户,众议院和个人资料与他们之间的以下关联:CakePHP:如何根据第二级关联条件查询结果?

  • 用户的hasMany屋(楼属于关联用户)
  • 用户hasOne档案(档案属于关联用户)

我想查询房屋(在HousesController类内),其关联的配置文件满足给定的配置文件条件。请看下面的例子:

假设性别是剖面模型的属性,我想检索所有的房屋,其所有者是男性。

我发现this的问题,这是足够接近我寻找。在我的情况下,模型之间的关系更复杂(House belongsTo User hasOne Profile),我无法使其工作。我已经试过这样的事情,没有任何的运气:

$this->House->find('all', array(
        'contain' => array(
         'User' => array(
          'Profile' => array(
           'conditions' => array(
            'Profile.gender' => 'male' 
)))))); 

以上调用返回所有的房屋,并在案件中的性别是男的,它包括在结果的各个用户的个人资料。否则,用户个人资料将保持为空。我真正需要的是返回只有房主是男性。

我已经实际使用'连接'选项Model::find()函数实现它,但我想知道是否可能没有使用'连接',如果是,如何?

回答

2

我会建议明确宣布使用bindModel法的关系。

你可以从你的房子做控制器像这样:

/** 
* Bind the models together using explicit conditions 
*/ 
$this->House->bindModel(array(
    'belongsTo' => array(
    'User' => array(
     'foreignKey' => false, 
     'conditions' => array('House.user_id = User.id') 
    ), 
    'Profile' => array(
     'foreignKey' => false, 
     'conditions' => array('Profile.user_id = User.id') 
    ) 
) 
)); 

/** 
* Standard find, specifying 'Profile.gender' => 'male' 
*/ 
$houses = $this->House->find('all', array(
    'conditions' => array(
    'Profile.gender' => 'male' 
) 
)); 
+1

谢谢你这个答案。这正是我正在寻找的! 我想补充一点,如果你想使用paginate而不是find,Model :: bindModel()函数的第二个参数必须设置为false。 – recu