Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cakephp complex query multiple 'OR' condition

Tags:

sql

cakephp

i want to make query like this with cakephp:

WHERE text LIKE '%keyword%' 
AND 
(
    (text LIKE '%something%') 
    OR (text LIKE '%something%') 
    OR (...)
) 
AND 
(
    (text LIKE '%other%') 
    OR (text LIKE '%other%') 
    OR (...)
) 
NOT 
(
    (text LIKE '%dont include%') 
    OR (text LIKE '%dont include%') 
    OR (...)
)

this is my code for $conditions:

$conditions = array
(
    'Tweet.text LIKE' => '%keyword%',
    'AND' => array(
        array(
            'OR' => array(
                // topic
                array('Tweet.text LIKE' => '%something%'),
                array('Tweet.text LIKE' => '%something%')
            )
        ),
        array(
            'OR' => array(
                // sentiment
                array('Tweet.text LIKE' => '%other%'),
                array('Tweet.text LIKE' => '%other%')
            )
        )
    ),
    'NOT' => array(
        array('Tweet.text LIKE' => '%dont include%'),
        array('Tweet.text LIKE' => '%dont include%')
    )
);

i am displaying the result with Debugger::dump() method, and the result is just using the last 'OR' condition, not both 'OR' conditions:

array(
    'Tweet.text LIKE' => '%keyword%',
    'OR' => array(
        (int) 0 => array(
            'Tweet.text LIKE' => '%other%'
        ),
        (int) 1 => array(
            'Tweet.text LIKE' => '%other%'
        )
    ),
    'NOT' => array(
        (int) 0 => array(
            'Tweet.text LIKE' => '%dont include%'
        ),
        (int) 1 => array(
            'Tweet.text LIKE' => '%dont include%'
        )
    )
)

My question is, how do I make a query such that use both 'OR' condition?

Pls reply as soon as possible.. Thanks in advance :)

like image 801
maswahyu Avatar asked Dec 12 '22 19:12

maswahyu


1 Answers

Try the following:

$conditions = array(
    'Tweet.text LIKE' => '%aa%',  //implied and
    array( //implied and
        'or' => array(
            array('Tweet.text LIKE' => '%11%'),
            array('Tweet.text LIKE' => '%22%'),
            array('Tweet.text LIKE' => '%33%'),
            ...
        )   
    ),
    array( //implied and
        'or' => array(
            array('Tweet.text LIKE' => '%123%'),
            array('Tweet.text LIKE' => '%456%'),
            array('Tweet.text LIKE' => '%789%'),
            ...
        )   
    )
    'not' => array(
        'or' => array(
            array('Tweet.text LIKE' => '%x%'),
            array('Tweet.text LIKE' => '%y%'),
            array('Tweet.text LIKE' => '%z%'),
            ...
        )   
    )
)

would be

text LIKE aa 
    AND ( either 11, 22, 33 ) 
    AND (either 123, 456, 789) 
    BUT NOT (x || y || z)`

Any array that does not specify or, and or not is and. No need to specify it manually.

like image 186
dogmatic69 Avatar answered Jan 01 '23 01:01

dogmatic69