我的数据库中有以下格式
产品
二、名称
专卖店Id
有以下记录
产品1-商店1
产品2-商店1
产品3-商店3
产品4-商店1
产品5-商店2
产品6-商店2
产品7-商店1
产品8-商店1
产品9-商店3
产品10-商店3
我想执行一个查询,将结果与"Id Store“交替使用,如下所示:
产品1-商店1
产品5-商店2
产品3-商店3
产品2-商店1
产品6-商店2
产品9-商店3
产品4-商店1
产品10-商店3
产品7-商店1
产品8-商店1
这份清单仍将被传阅。
发布于 2017-11-07 17:29:51
您可能需要这样做,这就是Rails。您将希望将所有不同的商店分组到不同的数组中。然后使用嵌套循环将每个数组的第一条记录弹出,直到它们都为空。我猜大多数这样的情况都会发生在Rails中,只有一两次对数据库的查询。
就像这样:
# Initialize product grouping hash
grouped_products = {}
# Produces hash of product arrays.
# Each array contains all of the products for a shop.
Products.all.order(:shop_id, :name).each do | product |
grouped_products[product.shop_id] = [] if grouped_products[product.shop_id].nil?
grouped_products[product.shop_id] << product
end
# Now we turn all of our grouped arrays into enumerators
grouped_products.each_key do | key |
grouped_products[key] = grouped_products[key].each
end
alternating_products = []
# Here we build the alternating products array
loop do
# Get the next product from the top of each grouped array
grouped_products.each_key do |key|
# Add the next product from the current array to the alternating array
begin
alternating_products << grouped_products[key].next
# If at the end of the current array, remove it from the hash
rescue StopIteration
grouped_products.except! key
end
end
# Stop looping when all arrays are empty and removed from hash
break if grouped_products.empty?
end
alternating_products我还没有测试上面的代码,所以它可能需要一些调整。
这需要循环遍历整个数据集两次。
因为这会返回一个有序数组,所以您可以相当容易地分页。例如:要获得前10条记录,请使用alternating_products[0..9]。要获得第二组10条记录,请使用alternating_products[10..19]等等。
https://stackoverflow.com/questions/47162151
复制相似问题