简体   繁体   中英

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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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