找到使用包含条件

时间:2017-12-22 19:11:45

标签: php cakephp cakephp-2.0 cakephp-2.3

你好,我有以下型号

Restaurant(id, name)
RestaurantMenu(id, name, restaurant_id) [每家餐厅都有很多主菜单]
RestaurantMenuItem(id, name, restaurant_menu_id) [每个菜单都有许多菜单项]

我需要找到至少有1 RestaurantMenu的{​​{1}}。如果没有那么它也不应该得到RestaurantMenuItem。它给了我空的数组RestaurantMenu,这是我不想要的。我不想要一个空物。

RestaurantMenuItem

1 个答案:

答案 0 :(得分:0)

这可以通过在INNER收容中对RestaurantMenuItemRestaurantMenu加入来实现。只有当至少存在一个关联的RestaurantMenu行时才会选择RestaurantMenuItem,这应该满足您的两个条件。

不幸的是,包含没有joinsgroup选项,因此必须通过手动查询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关联配置。

另见