gpt4 book ai didi

sql - ActiveRecord .missing - 为什么这不起作用?

转载 作者:行者123 更新时间:2023-12-05 05:38:55 25 4
gpt4 key购买 nike

在 Rails 6.1 上工作

我有这个基类:

class Post < ApplicationRecord
end

这两个子类代表了面对面的类(class)和直播:

class Live < Post
belongs_to :in_person_live,
foreign_key: :live_of_in_person_live_id,
class_name: 'InPersonLive',
required: false,
inverse_of: :online_live,
touch: true
end

class InPersonLive < Post
has_one :online_live,
class_name: 'Live',
foreign_key: 'live_of_in_person_live_id',
inverse_of: :in_person_live,
touch: true
end

我想查询没有直播的面授类(class)。

我想到了这个,似乎可行:

InPersonLive.where.not(id: Live.where.not(live_of_in_person_live_id: nil).select(:live_of_in_person_live_id)).count 

但想知道为什么这不起作用:

InPersonLive.where.missing(:online_live).count 

我希望 .missing 返回相同的结果,但它总是返回 0。

两种情况下生成的 SQL 都不同,但我还是不明白为什么结果不同,在我看来它们应该返回相同的集合。

InPersonLive.where.not(id: Live.where.not(live_of_in_person_live_id: nil)).count 生成:

SELECT COUNT(*) FROM "posts" WHERE "posts"."type" = $1 AND "posts"."id" NOT IN (SELECT "posts"."live_of_in_person_live_id" FROM "posts" WHERE "posts"."type" = $2 AND "posts"."live_of_in_person_live_id" IS NOT NULL)  [["type", "InPersonLive"], ["type", "Live"]]

InPersonLive.where.missing(:online_live).count 生成:

SELECT COUNT(*) FROM "posts" LEFT OUTER JOIN "posts" "online_lives_posts" ON "online_lives_posts"."live_of_in_person_live_id" = "posts"."id" AND "online_lives_posts"."type" = $1 WHERE "posts"."type" = $2 AND "posts"."id" IS NULL  [["type", "Live"], ["type", "InPersonLive"]]

最佳答案

你好@dwaynemac。

不知道你有没有映射或者反向查询

也许 InPersonLive 属于 LiveLive has_one有_很多。或者你应该查询 Live.where.missing(:in_person_live).count

因此,类似地,Something.where.missing(:thing) 应该生成相同的查询。

因为,如果您想在 missing 之前进行测试,您可以按照以下方式进行操作:

Live.left_joins(:in_person_live).where(in_person_live: { id: nil } )

关于sql - ActiveRecord .missing - 为什么这不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72820409/

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