Search code examples
phpmysqlsqlormkohana

How to display query assembled by ORM?


How to display query assembled by ORM ?

Example: SELECT article.id AS article:id, article.name AS article:name

I'm using the code below:

$query=DB::select('categories.*', 
                    array(DB::expr('COUNT(categories.id)'), 'total'),
                    array(DB::expr('MIN(displays.price)'), 'min_price'),
                    array(DB::expr('MAX(displays.price)'), 'max_price'),
                    array(DB::expr('SUM(displays.is_offer)'), 'is_offer')
            )
            ->from('categories')
                ->join('category_products', 'INNER')
                ->on('categories.id', '=', 'category_products.category_id')
                ->join('displays', 'INNER')
                ->on('category_products.product_id', '=', 'displays.product_id')
            ->where('displays.active', '>=', 1)
            ->group_by('categories.id')
            ->order_by('parent')
            ->order_by('total', 'desc');

Solution

  • Let's see, you're using DB::select() which returns a Database_Query_Builder_Select instance. In the doc it says

    Database query builder for SELECT statements. See Query Builder for usage and examples.

    And if you do see, you'll see

    echo Debug::vars((string) $query);
    // Should display:
    // SELECT `username`, `password` FROM `users` WHERE `username` = 'john'
    

    which makes sense once you see the __toString() from Database_Query_Builder_Select.

    So

    echo (string) $query;
    

    should give you the query.