将多个 sql 结果值分配给同一个键
Assigning multiple sql result values to the same key
我有一个 sql 这种形式的结果:
Id Amount1 Amount2 Amount3
1 10 10 12
2 20 13 14
3 30 15 15
我正在尝试将 Id 存储在 Key 中,将所有其他值存储在 value 中
像这样:
{1=>{:Amount1=>"10", :Amount2=>"10", :Amount3=>"12"}, 2=>{:Amount1=>"20", :Amount2=>"13", :Amount3=>"14"}}
这是我目前拥有的:
hashn = Hash.new
sqlresult.each { |x|
hashn[x['PPS_Id']] = x['Gift_Card_Amount1']
hashn[x['PPS_Id']] = x['Gift_Card_Amount2']
hashn[x['PPS_Id']] = x['Gift_Card_Amount3']
}
我相信这会覆盖以前的值,你能帮忙吗?
假设您的 Sql 结果是一个活动记录集合,这应该有效:
required_hash = {}
sqlresult.each do |obj|
required_hash[obj.id] =
{ amount1: obj.amount1, amount2: obj.amount2, amount3: obj.amount3 }
end
required_hash
您也可以将数组分配给哈希键
类似下面的内容
hashn= {}
sqlresult.each { |x|
hashn[x['PPS_Id']] = [] unless hashn[x['PPS_Id']]
hashn[x['PPS_Id']] << x['Gift_Card_Amount1']
hashn[x['PPS_Id']] << x['Gift_Card_Amount2']
hashn[x['PPS_Id']] << x['Gift_Card_Amount3']
}
我有一个 sql 这种形式的结果:
Id Amount1 Amount2 Amount3
1 10 10 12
2 20 13 14
3 30 15 15
我正在尝试将 Id 存储在 Key 中,将所有其他值存储在 value 中
像这样:
{1=>{:Amount1=>"10", :Amount2=>"10", :Amount3=>"12"}, 2=>{:Amount1=>"20", :Amount2=>"13", :Amount3=>"14"}}
这是我目前拥有的:
hashn = Hash.new
sqlresult.each { |x|
hashn[x['PPS_Id']] = x['Gift_Card_Amount1']
hashn[x['PPS_Id']] = x['Gift_Card_Amount2']
hashn[x['PPS_Id']] = x['Gift_Card_Amount3']
}
我相信这会覆盖以前的值,你能帮忙吗?
假设您的 Sql 结果是一个活动记录集合,这应该有效:
required_hash = {}
sqlresult.each do |obj|
required_hash[obj.id] =
{ amount1: obj.amount1, amount2: obj.amount2, amount3: obj.amount3 }
end
required_hash
您也可以将数组分配给哈希键
类似下面的内容
hashn= {}
sqlresult.each { |x|
hashn[x['PPS_Id']] = [] unless hashn[x['PPS_Id']]
hashn[x['PPS_Id']] << x['Gift_Card_Amount1']
hashn[x['PPS_Id']] << x['Gift_Card_Amount2']
hashn[x['PPS_Id']] << x['Gift_Card_Amount3']
}