你好,我有以下型号
Restaurant(id, name)
RestaurantMenu(id, name, restaurant_id)
[每家餐厅都有很多主菜单]
RestaurantMenuItem(id, name, restaurant_menu_id)
[每个菜单都有许多菜单项]
我需要找到至少有1 RestaurantMenu
的{{1}}。如果没有那么它也不应该得到RestaurantMenuItem
。它给了我空的数组RestaurantMenu
,这是我不想要的。我不想要一个空物。
RestaurantMenuItem
答案 0 :(得分:0)
这可以通过在INNER
收容中对RestaurantMenuItem
加RestaurantMenu
加入来实现。只有当至少存在一个关联的RestaurantMenu
行时才会选择RestaurantMenuItem
,这应该满足您的两个条件。
不幸的是,包含没有joins
和group
选项,因此必须通过手动查询RestaurantMenu
数据来解决此问题,这应该是在您的情况下非常简单,因为您只选择一个Restaurant
(顺便说一下,在这种情况下,您应该使用first
查找器而不是all
查找器:
$restaurant = $this->find('first', array(
'conditions' => array(
'Restaurant.id' => $restaurant_id,
),
'recursive' => 0
));
if ($restaurant) {
// RestaurantMenu needs to have the containable behavior attached
// in order for this to work
$restaurant['RestaurantMenu'] = $this->RestaurantMenu->find('all', array(
'contain' => array(
'RestaurantMenuItem'
),
'joins' => array(
array(
'table' => 'restaurant_menu_item',
'alias' => 'RestaurantMenuItem',
'type' => 'INNER',
'conditions' => array(
'RestaurantMenu.id = RestaurantMenuItem.restaurant_menu_id'
)
)
),
'conditions' => array(
'RestaurantMenu.restaurant_id' => $restaurant_id,
),
'group' => array(
'RestaurantMenu.id'
)
));
}
return $restaurant;
或使用finderQuery
选项定义包含联接的自定义查询:
return $this->find('all', array(
'contain' => array(
'RestaurantMenu' => array(
'finderQuery' => '
SELECT
RestaurantMenu.*
FROM
restaurant_menus AS RestaurantMenu
INNER JOIN
restaurant_menu_items AS RestaurantMenuItem ON
RestaurantMenuItem.restaurant_menu_id = RestaurantMenu.id
WHERE
RestaurantMenu.restaurant_id IN ({$__cakeID__$})
GROUP BY
RestaurantMenu.id
',
'RestaurantMenuItem'
)
),
'conditions' => array(
'Restaurant.id' => $restaurant_id,
)
));
这也适用于RestaurantMenu
模型中的Restaurant
关联配置。
另见