使用带有cakephp的sql中的连接从多个表中检索信息

时间:2015-09-07 19:13:45

标签: mysql cakephp join

我的桌面结构如下 recipies
类别
成分(含category_id)
recipies_categories
recipies_ingredients

使用 cakephp 我想检索指定配方的指定类别的成分。例如,我有 -

recipies:recp1,recp2,recp3
类别:CAT1,CAT2,CAT3
ingredeints:ING1,ING2,ing3
recipies_categories:recp1-CAT1,recp2-CAT2,recp2-CAT3,recp3-CAT3
ingredients_categories:ING1-CAT1,ING2-CAT2
给定recipe = recp2,category = cat1或cat3我应该没有成分
给定recipe = recep2,category = cat2我应该得到ing2

我尝试过使用连接的各种方法但无法获得结果。有人可以帮忙吗?

1 个答案:

答案 0 :(得分:0)

        $settings = array();
        $settings['recursive'] = 1;
        if (!empty($selected_categories)) {
            $this->Ingredient->Behaviors->load('Containable');
            $settings['conditions'] = array(
                'Ingredient.category_id' => $selected_categories //array containing selected catagory ids
            );
            $settings['contain'] = array(
                'Category' => array('id', 'name')
            );
        }
        $settings['joins'] = array(
            array('table' => 'recipes_ingredients',
                'alias' => 'RecipesIngredient',
                'type' => 'INNER',
                'conditions' => array(
                    'RecipesIngredient.ingredient_id = Ingredient.id',
                    'RecipesIngredient.recipe_id' => $recipe_id //selected recipe
                )
            )
        );
        $this->Paginator->settings = $settings;
        $ingredients = $this->Paginator->paginate($this->Ingredient);