如何在hasMany关联中使用CakePHP 2?

时间:2012-08-12 22:02:33

标签: cakephp search find relationship has-many

我知道这是一个古老的问题,但我似乎无法让它发挥作用。

我有这些关系:
用户有很多责任 负责任所属用户

我需要通过我的用户模型,执行以下搜索:

$users = $this->User->find('all', array('conditions' => array('Responsible.email' => $responsible_email));

但是这不起作用,它会在clouse的地方抛出一个“Unknown column'Responsible.email'。”

我的真实代码是这样的:

    $conditions = array();

    if (!empty($params['filter_by_name'])) {
        $conditions[] .= "LOWER(CONCAT(Profile.name, ' ', Profile.surname)) LIKE '%".$params['filter_by_name']."%'";
    }

    if (!empty($params['filter_by_email'])) {
        $conditions[] .= "LOWER(User.email) = '".$params['filter_by_email']."'";
    }

    if (!empty($params['filter_by_responsible_email'])) {
        $conditions[] .= "LOWER(Responsible.email) = '".$params['filter_by_responsible_email']."'";
    }

    $results = $this->User->find('all', array('conditions' => $conditions));

我已经在很多方面进行了搜索和尝试,但我无法使其发挥作用,我该怎么做?

编辑:

我能够使用可包含的内容来执行此操作,但它也会返回空白负责任的用户...

1 个答案:

答案 0 :(得分:1)

得到它:

       $options['joins'] = array(
            array(
                'table' => 'responsibles',
                'alias' => 'Responsible',
                'type' => 'INNER',
                'conditions' => array("User.id = Responsible.user_id")
            )
        );

        $conditions[] .= "Responsible.email = '".$params['filter_by_responsible_email']."'";

        $options['conditions'] = $conditions;

        $results = $this->User->find('all', $options);

运作良好:)