简体   繁体   中英

Lithium framework multiple 'or' statements in a query (using mongoDB)

I have started work with lithium framework + mongoDB recently. I want to do a really simple query which contains multiple or statements. I have articles in the DB with publish_up and publish_down fields. I want to fetch only those records/documents which pulbis_down field is highert than now OR null AND publish_up field lower than now OR null.

$items = $article::find('all', array(
    'conditions' => array(
        '$or' => array(
            '$gt' => array('publish_down', $mongoDateNow),
            'publish_down' => $mongDateNull
        ),
        '$or' => array(
            '$lt' => array('publish_up', $mongoDateNow),
            'publish_up' => $mongDateNull
        ),
    )
));

Of course this snippet is wrong hence the second or statement overwrites the first one (because the same array key). I tried to wrap them into an individual array but gives error. Any idea?

This query will fetch articles with (publish_down > now OR publish_down = null) AND (publish_up < now OR publish_up = null)

    $items = Articles::find('all', array(
        'conditions' => array(
            '$or' => array(
                array('publish_down' => array('$gt' => $mongoDateNow)),
                array('publish_down' => null)
            ),
            '$or' => array(
                array('publish_up' => array('$lt' => $mongoDateNow)),
                array('publish_up' => null)
            ),
        )
    ));

I don't know about lithium but in PHP you can use multiple $OR as below

$items = $article::find('all', array(
    'conditions' => array(
        '$or' => array(
        array(
            '$gt' => array('publish_down', $mongoDateNow),
            'publish_down' => $mongDateNull
        ),
        array(
            '$lt' => array('publish_up', $mongoDateNow),
            'publish_up' => $mongDateNull
        )
        ),
    )
));

I think the correct answer is:

'$and' => array(
    array(
        '$or'=>array(
            array('publish_up' => null),
            array('publish_up' => array('$lt' => $mongoDateNow))
        )
    ),
    array(
        '$or'=>array(
            array('publish_down' => null), 
            array('publish_down' => array('$gt' => $mongoDateNow))
        )
    )
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM