0

我正在使用 Kohana 3.3 ORM。我定义了以下模型:

class Model_Post extends ORM {

    protected $_primary_key = 'ObjID';

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

class Model_Category extends ORM {

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

现在,获取属于 ONE 类别的所有帖子非常容易:

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

我想知道如何获取属于类别 1 或 2 的所有帖子。我尝试了很多东西,但没有一个有效。我怎样才能让它工作?我有办法使用 ORM 模块而不是直接 SQL 查询吗?

4

2 回答 2

3

您可以向您的 Model_Post 添加一个函数,该函数将返回属于多个(或一个)类别的所有帖子。

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);
}

这将返回类别 1、3 和 5 中的所有帖子。

ORM::factory("Post")->in_categories(array(1, 3, 5))->find_all();
于 2013-09-27T19:05:49.593 回答
0

如果我正确理解了您的问题,您只需要两个 where 条件:

...    
$data = DB::select('*')->from('table_name')
      ->where_open()
          ->where('category_id','=',1)
          ->or_where('category_id','=',2)
      ->where_close()
...
于 2013-10-02T06:58:52.567 回答