【问题标题】:Rails - Query table with array of IDs and order based on the arrayRails - 使用 ID 数组和基于数组的顺序查询表
【发布时间】:2016-03-05 20:38:58
【问题描述】:

让我用简单的例子来描述。

我有一个数字列表:

例如:list = [ 3, 1, 2 ]

我在 DB 中有一个名为 Products 的表,其中有 3 行,product_id = 123

现在我需要查询Productslist(3,1,2) 排序,结果将是:

product_3 产品_1 产品_2

查询将如下所示: product.sort(list) 或 product.order(list) 或其他一些替代方案

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 rails-activerecord


    【解决方案1】:

    这应该适合你:

    list = [3, 1, 2]
    
    Product.where(product_id: list).sort_by { |p| list.find_index(p.product_id) })
    

    【讨论】:

      猜你喜欢
      • 2015-05-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多