首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在有一个关联的情况下提取列值?

如何在有一个关联的情况下提取列值?
EN

Stack Overflow用户
提问于 2019-06-18 14:18:37
回答 4查看 310关注 0票数 0

我有一个与QrCodehas_one关联的车辆模型。我希望提取qr_code的特定列,而不是选择所有列并映射单个值

我已经尝试了以下代码。

代码语言:javascript
复制
vehicle = Vehicle.first 
code = vehicle.qr_code.pluck(:value)

但这不是有效的查询

下面的代码将具有所需的值。

代码语言:javascript
复制
code = vehicle.qr_code.value 

但是这段代码构建的查询是

代码语言:javascript
复制
SELECT  "qr_codes".* FROM "qr_codes" WHERE "qr_codes"."codeable_id" = $1 AND "qr_codes"."codeable_type" = $2 LIMIT 1  [["codeable_id", 1], ["codeable_type", "Vehicle"]]

这是很昂贵的,因为它选择所有的列值,并且qr_codes表中只有很少的列存储大量数据。

以下是代码实现

代码语言:javascript
复制
class Vehicle < ActiveRecord::Base
  has_one :qr_code, as: :codeable
end

class QrCode < ActiveRecord::Base
  belongs_to :codeable, polymorphic: true
end

非预期查询:

代码语言:javascript
复制
SELECT  "qr_codes".* FROM "qr_codes" WHERE "qr_codes"."codeable_id" = $1 AND "qr_codes"."codeable_type" = $2 LIMIT 1  [["codeable_id", 1], ["codeable_type", "Vehicle"]]

预期查询:

代码语言:javascript
复制
SELECT  "qr_codes".value FROM "qr_codes" WHERE "qr_codes"."codeable_id" = $1 AND "qr_codes"."codeable_type" = $2 LIMIT 1  [["codeable_id", 1], ["codeable_type", "Vehicle"]]
EN

回答 4

Stack Overflow用户

发布于 2019-06-18 14:26:05

您可以使用如下查询来获取车辆首条记录及其二维码的值名称

代码语言:javascript
复制
Vehicle
      .left_outer_joins(:qr_code)
      .select("vehicles.*, 
              (SELECT qr_codes.value from qr_codes WHERE vehicles.id = qr_codes.codeable_id) as value_name")
      .limit(1)
票数 1
EN

Stack Overflow用户

发布于 2019-06-18 14:32:22

如果您有Vehicle实例:

代码语言:javascript
复制
QrCode.
  where(codeable: vehicle).
  pluck(:value).
  first

当您仅使用vehicle_id时:

代码语言:javascript
复制
Vehicle.
  left_joins(:qr_code).
  where(id: vehicle_id).
  pluck('qr_codes.value').
  first
票数 0
EN

Stack Overflow用户

发布于 2019-06-18 15:12:05

根据您预期的查询-

QrCode.where(codeable: Vehicle.first).pluck(:value).first

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56642783

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档