Search code examples
kohanakohana-3kohana-ormkohana-db

Kohana 3 ORM - group by case


I would like to achieve this query with the ORM query builder:

SELECT * FROM `products`
GROUP BY CASE `products`.`configurable` 
WHEN 'yes' THEN `products`.`id_configuration` 
ELSE `products`.`id` 
END

I know that this works:

$products = DB::query(Database::SELECT, '
    SELECT * FROM `products`
    GROUP BY CASE `products`.`configurable` 
    WHEN 'yes' THEN `products`.`id_configuration` 
    ELSE `products`.`id` 
    END
')->execute();

But it returns a mysql db result, and I would rather have an ORM list, otherwise I will have to instanciate all my ORM objects in a loop, resulting in poor performance... or...?

Is it possible? The ORM 'group_by' function looks very limited...


Solution

  • You should define what kind of DB result you want:

    $products = DB::query(Database::SELECT, '
        SELECT * FROM `products`
        GROUP BY CASE `products`.`configurable` 
        WHEN 'yes' THEN `products`.`id_configuration` 
        ELSE `products`.`id` 
        END
    ')
    ->as_object('Model_Product') // !!
    ->execute();
    

    Or, if you use it inside model, you can call ->as_object(get_class($this)) or ->as_object($this).