CakePHP:如何根据二级关联条件查询结果



假设我们有3个模型,User, House和Profile,它们之间有以下关联:

  • User hasMany House (House belongsTo User)
  • 用户有一个Profile (Profile belongsTo User)

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

假设性别是Profile模型的一个属性,我想检索所有房主为男性的房子。

我已经找到了这个问题,它足够接近我所寻求的。在我的例子中,模型之间的关系更复杂(House belongsTo User hasOne Profile),我无法让它工作。我试过这样做,没有任何运气:

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

上述调用返回所有房屋,如果性别为男性,则在结果中包含相应的用户配置文件。否则,用户配置文件将保持为空。我真正需要的是返回房主是男性的房子。

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

我建议使用bindModel方法显式声明关系。

你可以在Houses控制器中这样做:

/**
 * 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'
  )
));

最新更新