phpormkohanakohana-orm

ORM 'or_where' use


I'd like my ORM factory to return records where x = 1 and y is either equal to 1 or 2. I've tried a few variations with and_where, but it returns loads more than records than it should. The ORM is then stored in a php variable. Here's my current code

$tests = ORM::factory('Test')
    ->where('x', '=', 1)
    ->or_where('y', '=', 1)
    ->or_where('y', '=', 2)
    ->find_all();

Solution

  • You can group the OR statements via and_where_open()/and_where_close() like so (untested)

    $test = ORM::factory('Test')
        ->where('x', '=', 1)     // 1
        ->and_where_open()       // 2
        ->where('y', '=', 1)     // 3
        ->or_where('y', '=', 2)  // 4
        ->and_where_close()
        ->find_all();
    

    This should create a query like

    SELECT .. FROM .. WHERE x = 1   AND (  y=1   OR y=2  )
                            ^^^^^   ^^^^^  ^^^   ^^^^^^
                              1       2     3      4