Question

I'm using Kohana 3.3 ORM. I have the following models defined:

class Model_Post extends ORM {

    protected $_primary_key = 'ObjID';

    protected $_has_many = array(
        'categories' => array(
            'model'   => 'Category',
            'through' => 'posts2categories',
            'foreign_key' => 'post_id',
        ),
    );
}

and

class Model_Category extends ORM {

    protected $_has_many = array(
        'posts' => array(
            'model'   => 'Post',
            'through' => 'posts2categories',
            'foreign_key' => 'category_id',
        ),
    );
}

now, fetching all posts belonging to ONE category is very easy:

$posts = $categoriesQuery->where('category_id','=',1)->find()->posts->find_all();

I want to know how to fetch all posts belonging to category 1 OR 2. I tried many things, and non of them worked. How can I make it work? I there a way of doing it using the ORM module and not with a direct SQL query?

Was it helpful?

Solution

You could add one function to your Model_Post that will return all posts belonging to multiple (or one) categories.

public function in_categories($categories) 
{
        return $this->join("posts2categories")->on("posts2categories.post_id", "=", "posts.id")
            ->join("categories")->on("category.id", "=", "posts2categories.category_id")
            ->where("categories.id", "IN", $categories);
}

This will return all posts in categories 1, 3 and 5.

ORM::factory("Post")->in_categories(array(1, 3, 5))->find_all();

OTHER TIPS

if i understain your question correctly you just need two where conditions:

...    
$data = DB::select('*')->from('table_name')
      ->where_open()
          ->where('category_id','=',1)
          ->or_where('category_id','=',2)
      ->where_close()
...
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top