简体   繁体   English

在Paris ORM中创建查询

[英]Creating queries in Paris ORM

I have a collection of Recipes and each one contains Categories. 我有一些食谱,每个食谱都包含类别。 This are my models: 这是我的模型:

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');
    }
}

And the table to relate both: 与该表相关的两个:

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

Now I need to create a query to get all the Recipes that are under one/more categories. 现在,我需要创建一个查询来获取一个/多个类别下的所有食谱。 What is the way to achieve this? 如何做到这一点? I want to avoid making things like this: 我想避免做这样的事情:

$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);
}

Create filters? 创建过滤器? functions inside the models? 模型内部的功能? Is not possible to make it more elegant? 不可能使它更优雅吗?

That is pretty much how I would do it, but you can optimise in one way. 这几乎就是我的方法,但是您可以采用一种方式进行优化。 Add relation functions to your linking/many-to-many table. 将关系函数添加到链接/多对多表中。 Then instead of doing that extra query in your foreach loop you simply do: 然后,您只需执行以下操作即可:

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

So your CategoryRecipe model might look like: 因此,您的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');
    }
}

I haven't tested this code, but it should be what you're after I think. 我没有测试过这段代码,但是我认为应该是您想要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM