Kohana 3 ORM:如何使用2对多关系执行查询

时间:2010-07-20 02:22:49

标签: kohana kohana-3

我有一个产品模型,定义了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'Estrees'中的产品?

谢谢!

2 个答案:

答案 0 :(得分:0)

简单;你没有。你需要的是INNER JOIN,比如;

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

答案 1 :(得分:0)

在没有使用DB::expr的Kohana 3.1中,

会产生未知的列错误。

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