开发者

Kohana 3 ORM: How to perform query with 2 many to many relationships

开发者 https://www.devze.com 2023-01-07 19:49 出处:网络
I have a produ开发者_开发技巧cts model with 2 many to many relationships defined. protected $_has_many = array

I have a produ开发者_开发技巧cts model with 2 many to many relationships defined.

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

I need a query where I find products with a given foodcat id and a given foodgroup name. I know I can do the following to get all products with a given foodcat id

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

But how do I query for products in that foodcat that also are in the foodgroup 'Entrees'?

Thanks!


Simply; you don't. What you need is INNER JOIN, like;

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


in Kohana 3.1 without using DB::expr, will give unknown column error.

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

精彩评论

暂无评论...
验证码 换一张
取 消