0

我有一组食谱,每个都包含类别。这是我的模型:

class Recipe extends \Model {
    public static $_table = "recipe";

    public function categories() {
        return $this->has_many_through('Category');
    }
}

class Category extends \Model {
    public static $_table = "category";

    public function categories() {
        return $this->has_many_through('Recipe');
    }
}

以及将两者联系起来的表格:

class CategoryRecipe extends \Model {
    public static $_table = "category_recipe";
}

现在我需要创建一个查询来获取一个/多个类别下的所有食谱。实现这一目标的方法是什么?我想避免做这样的事情:

$results = $app['paris']->getModel('CategoryRecipe')
                        ->where_in("category_id",$selected_categories)
                        ->find_many();

foreach($results as $result) {
    $recipe = $app['paris']->getModel('Recipe')
                           ->where('id',$result->recipe_id)
                           ->find_one();
    var_dump($receta->name);
}

创建过滤器?模型内部的功能?是不是可以让它更优雅?

4

1 回答 1

0

这几乎就是我的做法,但您可以通过一种方式进行优化。将关系函数添加到链接/多对多表中。然后,您无需在 foreach 循环中执行该额外查询,您只需执行以下操作:

foreach($results as $result) {
    $recipe = $result->recipe()->find_one();
    var_dump($recipe)
}

所以你的CategoryRecipe模型可能看起来像:

class CategoryRecipe extends \Model {
    public static $_table = "category_recipe";

    public function recipe() {
        $this->belongs_to('Recipe', 'recipe_id');
    }

    public function category() {
        $this->belongs_to('Category', 'category_id');
    }
}

我还没有测试过这段代码,但它应该是你想的那样。

于 2014-02-28T12:13:21.123 回答