2013-09-27 31 views
0

我正在使用Kohana 3.3 ORM。我有以下型號定義:Kohana 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', 
     ), 
    ); 
} 

現在,獲取屬於一個類別的所有訊息很簡單:

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

我想知道如何將所有取屬於類別1或2的帖子。 我嘗試了很多東西,其中沒有一個能夠工作。我怎樣才能使它工作?我有使用ORM模塊而不是直接SQL查詢的方法嗎?

回答

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

如果我正確understain你的問題,你只需要兩個有條件的地方:

...  
$data = DB::select('*')->from('table_name') 
     ->where_open() 
      ->where('category_id','=',1) 
      ->or_where('category_id','=',2) 
     ->where_close() 
... 
相關問題