【问题标题】:Get column value from a different table using select使用 select 从不同的表中获取列值
【发布时间】:2019-12-29 11:15:36
【问题描述】:

我的交互器上有这个查询:

 Variant.where(code: context.codes)
        .joins("LEFT OUTER JOIN prices p
                ON p.variant_id = variants.id")
        .select("code,
                 actual_price,
                 selling_price,
                 p.cost")

返回:

#<Interactor::Context codes=["PRDCTA-V1", "PRDCTA-V2"], body=[#<Variant id: nil, selling_price: nil, code: "PRDCTA-V2", actual_price: nil>,
#<Variant id: nil, selling_price: #<BigDecimal:7ff1d13b9118,'0.1E3',9(18)>, code: "PRDCTA-V1", actual_price: nil>]

我不知道为什么prices 表中的p.cost 没有出现,这意味着我的选择是错误的。我尝试将其更改为costprices.cost 仍然不起作用。

我的预期输出应该是

[#<Variant id: nil, selling_price: nil, code: "PRDCTA-V2", actual_price: nil, cost:{value here}>,

【问题讨论】:

  • 它没有出现,但无论如何都可以访问,试试&lt;your_query&gt;.first.cost
  • @SebastianPalma 编辑:它确实出现了!但为什么?有没有办法可以将它包含在我的结果中?
  • 在内存中,但没有“推送”到变体对象。您可以迭代并调用该列名作为方法。还是您需要一种特殊的方式来表示它们?
  • 您可以使用.map(&amp;:attributes) 将记录列表转换为普通散列,这些具有密钥cost

标签: sql ruby postgresql ruby-on-rails-4


【解决方案1】:

试试这个,在选择中为成本分配别名

p.cost AS price_cost

然后,通过variants.first.price_cost获取它

或者,从attributes获取它

variants.first.attributes['cost']

将返还费用。

希望有帮助!

【讨论】:

    猜你喜欢
    • 2013-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-16
    • 2016-04-19
    • 1970-01-01
    相关资源
    最近更新 更多