gpt4 book ai didi

sql - Activerecord 查询未返回所有结果

转载 作者:行者123 更新时间:2023-12-04 22:07:40 25 4
gpt4 key购买 nike

我在 Rails 4 中遇到了 ActiveRecord 查询的问题:

我的模型:

class Addressee < ActiveRecord::Base
has_and_belongs_to_many :emails
end

class Email < ActiveRecord::Base
belongs_to :author, foreign_key: :from_id, class_name: "Addressee"
has_and_belongs_to_many :addressees
end

我的 schema.rb
  create_table "addressees", force: true do |t|
t.string "token", limit: nil
t.string "domain", limit: nil
t.string "email", limit: nil
t.string "name", limit: nil
t.datetime "created_at"
t.datetime "updated_at"
end

create_table "addressees_emails", force: true do |t|
t.integer "addressee_id"
t.integer "email_id"
t.datetime "created_at"
t.datetime "updated_at"
end

create_table "emails", force: true do |t|
t.string "message_id", limit: nil
t.integer "from_id"
t.string "subject", limit: nil
t.text "body"
t.datetime "date"
t.datetime "created_at"
t.datetime "updated_at"
end

我的查询:
# Returns correct emails
query_params = { "addressees.email" => "test@example.com" }
@emails = Email.includes(:addressees).where(query_params).references(:addressees)

我的问题:
# Returns only the addressee matching the email from query params
@emails.last.addressees
#<ActiveRecord::Associations::CollectionProxy [#<Addressee id: 12, token: "test", domain: "example.com", email: "test@example.com", name: nil, created_at: "2014-09-25 14:06:34", updated_at: "2014-09-25 14:06:34">]>

#Returns the wrong count
@emails.last.addressees.size
#=> 1

#Returns the correct count (because it does a new query)
@emails.last.addressees.count
#=> 3

我的问题:

如何修改查询以包含所有收件人,而无需执行其他查询?。我将 @emails var 传递给我的 json 序列化程序,现在它只包含 1 个收件人而不是全部 3 个。

最佳答案

@emails = Email.where('emails.id IN SELECT(email_id FROM addressees_emails WHERE addressee_id IN (SELECT id FROM addressees WHERE email IN (?)))', %w[test@example.com test2@example.com]).includes(:addressees)

关于sql - Activerecord 查询未返回所有结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26055212/

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