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

最后都变了- 提交于 2019-11-27 07:28:12

问题


I have a products 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!


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/3286539/kohana-3-orm-how-to-perform-query-with-2-many-to-many-relationships

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!