【问题标题】:Using Arel for ROR I am trying to query based on my Classes associated attributes使用 Arel 进行 ROR 我正在尝试根据我的类关联属性进行查询
【发布时间】:2017-09-30 03:17:41
【问题描述】:

我有一个Recipe 类和一个Ingredient 类,它们通过连接表RecipeIngredients 与has_many 连接到has_many。我正在尝试创建一些过滤器,并尝试按食谱包含的成分数量对我的食谱进行排序。我无法弄清楚正确的 SQL,我也在尝试使用 Arel 来找到我的答案。但此时我将采取任何适当的方式来查询这一点。反过来,我也会尝试 Query the Ingredients 得到他们有多少个食谱。

提前感谢您提供的任何帮助,我在查询时遇到了问题,今晚完全没有任何想法。谢谢。

【问题讨论】:

    标签: sql ruby-on-rails arel


    【解决方案1】:

    我会考虑使用 Arel 来解决这种过于复杂的问题。 ActiveRecord 本身,它是 Arel 之上的一层,可以很轻松地解决这个问题。

    我假设您有以下型号

    class Recipe
      has_many :recipe_ingredients
      ...
    end
    
    class RecipeIngredient
      has_one: :recipe
      has_one: :ingredient
      ...
    end
    
    class Ingredient
      has_many :recipe_ingredients
      ...
    end
    

    为了获得按成分数​​量排序的食谱,您必须生成以下 SQL 语句:

    SELECT 
      recipes.id
      ... 
      , recipes.[last_column_name]
      # optionally
      , COUNT(*) ingredients_count        
    FROM
      recipes
    OUTER JOIN
      recipe_ingredients
      ON
        recipe_ingredients.recipe_id = recipe.id
    GROUP BY
      ingredient_count DESC
    

    这可以通过

    Recipe
      .joins(:recipe_ingredients)
      .group(Recipe.column_names)
      .select(Recipe.column_names, 'COUNT(*) ingredients_count')
      .order('ingredients_count DESC') # Or ASC
    

    返回的 Recipe 实例将按成分数量排序。他们还将有一个额外的方法 ingredients_count 返回成分的数量。

    这也可以放在 Recipe 类的范围内。

    def self.ordered_by_ingredients_count
      joins(:recipe_ingredients)
      .group(column_names)
      .select(column_names, 'COUNT(*) ingredients_count')
      .order('ingredients_count DESC') # Or ASC
    end
    

    反之,一种成分的配方数量,只需交换一些名称:

    Ingredient
      .joins(:recipe_ingredients)
      .group(Ingredient.column_names)
      .select(Ingredient.column_names, 'COUNT(*) recipe_count')
      .order('recipe_count DESC') # Or ASC
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-10-11
      • 2020-04-04
      • 1970-01-01
      • 2011-09-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多