【问题标题】:CakePHP: How can I query for results based on 2nd level association conditions?CakePHP:如何根据二级关联条件查询结果?
【发布时间】:2011-11-29 13:22:58
【问题描述】:

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

  • 用户有很多房子(房子属于用户)
  • 用户拥有一个个人资料(个人资料属于用户)

我想查询房屋(在 HousesController 类中),其关联的 Profile 满足给定的 Profile 条件。考虑以下示例:

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

我找到了this 问题,这与我所寻求的非常接近。就我而言,模型之间的关系更复杂(House belongsTo User hasOne Profile),我无法让它工作。我尝试过这样的事情,但没有任何运气:

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

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

我实际上已经使用Model::find() 函数的'joins' 选项实现了它,但我想知道这是否可能不使用 使用'joins',如果可以,如何?

【问题讨论】:

    标签: php cakephp


    【解决方案1】:

    我建议使用 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'
      )
    ));
    

    【讨论】:

    • 感谢您的回答。这正是我想要的!我想补充一点,如果要使用分页而不是查找,Model::bindModel()函数的第二个参数必须设置为false
    猜你喜欢
    • 2020-08-28
    • 1970-01-01
    • 1970-01-01
    • 2019-11-18
    • 2012-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多