cakephp find all condition AND OR

2020-05-27 04:10发布

问题:

Below is my condition:

'OR' =>
    array(
        'AND' => array(
            array('EventCompetitor.is_black' => 1),
            array('EventCompetitor.is_adult' => 1)
        ),
        'AND' => array(
            array('EventCompetitor.is_black' => 0),
            array('EventCompetitor.is_adult' => 0)
        ),
    ),

When I debug my query, it comes something like this, which is wrong:

AND ((`EventCompetitor`.`is_black` = 0) AND (`EventCompetitor`.`is_adult` = 0)) AND

Now, that's not what I want, I want it something like this:

((`EventCompetitor`.`is_black` = 1) AND (`EventCompetitor`.`is_adult` = 1)) OR ((`EventCompetitor`.`is_black` = 0) AND (`EventCompetitor`.`is_adult` = 0))

Any idea, how can I achieve it?

Thanks !

回答1:

your subkeys in your "OR" keyed array are the same name, with the second key effectively overwriting the first. you need to encapsulate those "AND" conditions in their own arrays, to prevent the key collision.

eg. instead of:

'OR' =>
        array(
               'AND' => array(
                              array('EventCompetitor.is_black' => 1),
                              array('EventCompetitor.is_adult' => 1)
                        ),
               'AND' => array(
                              array('EventCompetitor.is_black' => 0),
                              array('EventCompetitor.is_adult' => 0)
                        ),
             ),

do:

'OR' =>
        array(
               array('AND' => array(
                              array('EventCompetitor.is_black' => 1),
                              array('EventCompetitor.is_adult' => 1)
                        )),
               array('AND' => array(
                              array('EventCompetitor.is_black' => 0),
                              array('EventCompetitor.is_adult' => 0)
                        )),
             ),


回答2:

I haven't tested it, but I think you need the following:

'OR' =>
    array(
        array(
            array('EventCompetitor.is_black' => 1),
            array('EventCompetitor.is_adult' => 1)
        ),
        array(
            array('EventCompetitor.is_black' => 0),
            array('EventCompetitor.is_adult' => 0)
        )
    )

AND is implied between conditions, you only have to define OR groups



回答3:

I think you need an extra array() in there, im not sure but its worth a try:

'OR' =>
    array(
        array(
            'AND' => array(
                array('EventCompetitor.is_black' => 1),
                array('EventCompetitor.is_adult' => 1)
            )
        ),
        array(
            'AND' => array(
                array('EventCompetitor.is_black' => 0),
                array('EventCompetitor.is_adult' => 0)
            )
        )
    ),