【问题标题】:Rails - Conditions Include Multiple Items In An ArrayRails - 条件包括数组中的多个项目
【发布时间】:2011-04-25 18:49:43
【问题描述】:
p = Person.find_by_id(1, :include => :bags, :conditions => ['bag.id in (?), [3,4])

我想知道如何确保此查询仅在同时存在“items.id”“3”和“4”而不是“3”或/和“4”时才有效。

谢谢

【问题讨论】:

  • 请多解释一下您要完成的工作。
  • 在普通 SGL 中:SELECT * FROM people p INNER JOIN bag_persons b1 ON b1.person_id = p.id INNER JOIN bag_persons b2 ON b2.person_id = p.id WHERE b1.bag_id = 3 AND b2。 bag_id = 4 关键是你需要加入 2 次才能同时搜索两个包。也许有一种更简洁的方法可以在 rails 中编写它,但是使用 :joins 和 :conditions 您将能够将此查询转换为 find 语法。
  • 顺便说一句,:include 主要用于预取结果 person 对象中的包,所以如果你在这个请求之后不访问它的包,:joins 就足够了。
  • 设置是什么? person has_many :bags and bag belongs_to person?
  • @jacob 我正在尝试运行一个查询,只有当他们有相关的包时才会返回该人。 @marko 设置是“person has_many :persons_bags, has_many :bags, :through => :peoples_bags”, “peoples_bag belongs_to :person, belongs_to :bag”和“bags has_many :peoples_bag”

标签: ruby-on-rails join conditional-statements


【解决方案1】:

您需要手动构建到 bag_persons 表的 2 个内部连接:

Person.find_by_id(1, :joins => "INNER JOIN bags_persons bp1 ON bp1.person_id=persons.id INNER JOIN bags_persons bp2 ON bp2.person_id=persons.id", :conditions => "bp1.bag_id=3 AND bp2.bag_id=4")

希望对你有帮助

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-21
    • 2011-09-12
    • 1970-01-01
    • 2013-06-27
    • 1970-01-01
    • 1970-01-01
    • 2017-09-12
    相关资源
    最近更新 更多