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?
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();