dongshungai4857 2014-07-01 20:57
浏览 37
已采纳

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

I'm using CakePHP 2.3.8 and trying to find Users who have not configured options. If there is no entry found for User 1 in the options table, then that user should be selected

The tables

users
id    |    username   |      password     |category_id    |     registration_date    


options
id    |    user_id    |    display_email   |    allow_contact

A user does not have to be entered in the options table. What I'm trying to do is find all of the users that do not have an entry in the options table.

$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条回答 默认 最新

  • duanjiushu5063 2014-07-01 22:00
    关注

    First change your join type to left. This will get you all users, even those that have no options. An inner join will only get those users that have an option -- almost the opposite of what you want.

    Then add a condition to look for rows where Option.id is null. Users that do not have an option associated with them will have null for all the columns that came from Option.

    $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'
                          )
                   )
            )
      );
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源