2010-07-20 49 views
1

我有一個產品模型,其中定義了2個多對多關係。Kohana 3 ORM:如何使用2多對多關係執行查詢

protected $_has_many = array 
(
'foodcats' => array('model' => 'foodcat', 'through' => 'products_foodcats'), 
'foodgroups' => array('model' => 'foodgroup', 'through' => 'products_foodgroups') 
) 

我需要一個查詢,其中找到帶有給定foodcat id和給定食物組名稱的產品。 我知道我可以做下面讓所有的產品與給定foodcat ID

$foodcat = ORM::factory('foodcat',$foodCatId); 
$products = $foodcat->products->find_all(); 

但我怎麼在這foodcat也都在foodgroup「主菜」查詢產品?

謝謝!

回答

0

簡單地;你沒有。你需要的是INNER JOIN,就像;

ORM::factory('product') 
->join('foodcats','INNER') 
->on('foodcats.id','=',$foodcats_id) 
->join('foodgroups','INNER') 
->on('foodgroups.name','=',$foodgroups_name) 
->find_all(); 
0

in Kohana 3.1沒有使用DB::expr,會給出未知列錯誤。

ORM::factory('product') 
->join('foodcats','INNER') 
->on('foodcats.id','=', DB::expr($foodcats_id)) 
->join('foodgroups','INNER') 
->on('foodgroups.name','=', DB::expr($foodgroups_name)) 
->find_all();