gpt4 book ai didi

mysql - 如何将查询直接传递给where条件?

转载 作者:行者123 更新时间:2023-11-29 12:27:23 27 4
gpt4 key购买 nike

  • 从另一个查询中获取technology_id。它是通过一个错误实现的。
  • 有没有办法缩短查询。(嵌套查询)

查询:

Vendor.where(vendors: {company: nil}).joins(technologies_vendors: {technology_id: "Technology.select(:technology_id).where(url: 'ios',is_verified: true)"})

错误:

ActiveRecord::ConfigurationError: Association named 'technology_id' was not found on TechnologiesVendor; perhaps you misspelled it?

最佳答案

我假设您已经设置了三个具有以下关系的模型:

Vendor has_many technologies_vendors
Technology has_many technologies_vendors
TechnologiesVendor belongs_to vendor
TechnologiesVendor belongs_to technology

您的条件是:

vendors should have 'nil' company
technologies should be verified and have 'ios' url

在这种情况下,这就是您想要的:

Vendor.
joins(technologies_vendors: :technology).
where({
vendors: {company: nil},
technologies: {url: 'ios', is_verified: true}
})

但是您也可以非常轻松地使用 merge 方法。

Vendor.
joins(technologies_vendors: :technology).
where(vendors: {company: nil}).
merge( Technology.where(technologies: {url: 'ios', is_verified: true}) )

但是,在这两种情况下,您都必须消除或稍微修改第二个查询。

Learn more about merge here.

关于mysql - 如何将查询直接传递给where条件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28107898/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com