2017-11-07 16 views
0

I持って私のデータベースレール5で交互にソートするクエリを作成するにはどうすればよいですか?

製品では次のフォーマット
- 名前
- ショップ1
製品2 - - 次のレコード


製品1とショップ同上

ショップ1
商品3 - ショップ3
商品4 - ショップ1
製品5 - ショップ2
商品6 - ショップ2
製品7 - ショップ1
製品8 - ショップ1
製品9 - ショップ3
製品10-ショップ3


I結果を「Id Store」と交互に表示するクエリを実行したい場合は、次のようなものを入力します。

製品1 - ショップ1
製品5 - ショップ2
製品3 - ショップ3
製品2 - ショップ1
商品6 - ショップ2
製品9 - ショップ3
製品4 - ショップ1
製品10-ショップ3
製品7 - ショップ1
製品8 - ショップ1

この一覧は、まだページングされます。

+0

あなたは3つずつ交替したいと思っていますか?また、これは宿題の問題ですか? –

+0

こんにちは@TomAranda、回答ありがとう 私が取り組んでいるプロジェクトです。 店舗数は3に限定されず、5,10,15以上で変更できます。 私はランダムな順序付けを使用し、検索が行われた後にハッシュを調整することができますが、それでも問題になる可能性があります。ショップ1の製品のみになると間違ったリストになります。 このような理由から、私は結果が既にクエリによって変更された状態にする方法を探しています –

+0

私はあなたが複数のステップでこれを行う必要があると思います。 1つのクエリが機能するかどうかはわかりません。私はそれについて考える必要があります。 –

答えて

0

おそらくこれはRailsである必要があります。あなたは、異なる店舗のすべてを別々の列にまとめたいと思うでしょう。次に、ネストされたループを使用して、すべての配列が空になるまで最初のレコードをポップします。私は、データベースへのクエリが1つまたは2つだけで、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 

私は上記のコードをテストしていないので、いくつかの微調整が必​​要な場合があります。

これは、データセット全体を2回ループする必要があります。

これは順序付き配列を返すので、かなり簡単に改ページできます。たとえば、最初の10レコードを取得するには、alternating_products[0..9]を使用します。 10レコードの2番目のセットを取得するにはalternating_products[10..19]などを使用します。

+0

ここでコードをテストすれば、最初のページだけが店舗から来ていれば、店舗からの商品があるだけなので切り替えできませんでした –

+0

私の恐れはそれですそれは大規模な考え方では非常に重いですが、今のところ私はこのようにします。助けをありがとう= D –

+0

本当に効率的ではありませんが、私が考えることができる最高の解決策です瞬間。 –

関連する問題