Question

I'm trying to get Kohana's ORM to construct a query that returns a record, but also counts the related rows in another table. Were I doing it in a manual query, the result would be like so:

SELECT
*,
(SELECT COUNT(answer_id) FROM user_question_answers WHERE answer_question_id = question_id) as answer_count
FROM users_questions
WHERE question_user_id = 13

Is it possible to add raw SQL to any parts of the Kohana ORM model?

Thanks

Was it helpful?

Solution

Ok, I figured it out. I extended the ORM driver by creating classes/orm.php, which contains the following:

<?php defined('SYSPATH') or die('No direct access allowed.');

class ORM extends Kohana_ORM {
    public function add_subquery($query) {
        $this->_db_pending[] = array(
            'name' => 'select',
            'args' => array(DB::expr($query)),
        );

        return $this;
    }
}

Then, in my ORM call, I did the following:

$questions = ORM::factory('question')
    ->add_subquery('(SELECT COUNT(answer_id) FROM user_question_answers WHERE answer_question_id = question_id) as answer_count')
    ->where('question_user_id', '=', $this->current_user->id)
    ->find_all();

I'm still figuring out all the ins and outs of Kohana, and I'm concerned that using DB::expr() might pose a security risk should this be used with user-submitted data. But I won't be using it with anything from a user, so I'm ok for now.

If anyone has a better solution I'd be interested to see how you would solve the problem.

OTHER TIPS

If you do the subquery with query builder first and push that in your function ->add_subquery() you should be fine.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top