Cakephp搜索不存在的表条目的条件

时间:2014-07-01 20:57:54

标签: php mysql cakephp

我正在使用CakePHP 2.3.8并尝试查找尚未配置选项的用户。如果在选项表中找不到用户1的条目,则应选择该用户

表格

users
id    |    username   |      password     |category_id    |     registration_date    


options
id    |    user_id    |    display_email   |    allow_contact

不必在选项表中输入用户。我想要做的是找到所有在选项表中没有条目的用户。

$this->paginate = array(
                        'conditions' => array(
                            'User.category_id' => $category_id,
                            //condition if the options table entry for the user is not set
                        ),
                        'joins' => array(
                            array(
                                 'table' => 'options',
                                 'alias' => 'Option',
                                 'type' => 'inner',
                                 'conditions' => array(
                                      'Option.user_id' => 'User.id'
                                 )
                            )
                        )
                     )

1 个答案:

答案 0 :(得分:1)

首先将您的联接类型更改为左侧。这将为您提供所有用户,即使是没有选项的用户。内部联接只会让那些有选项的用户 - 几乎与你想要的相反。

然后添加条件以查找Option.id为null的行。没有与之关联的选项的用户对于来自Option的所有列都将为null。

$this->paginate = array(
       'conditions' => array(
              'User.category_id' => $category_id,
              'Option.id' => null
        ),
        'joins' => array(
               array(
                     'table' => 'options',
                     'alias' => 'Option',
                     'type' => 'left',
                     'conditions' => array(
                           'Option.user_id' => 'User.id'
                      )
               )
        )
  );
相关问题