gpt4 book ai didi

mysql - 如何从 Rails 2 中不包含特定项目的多对多关系中选择特定记录?

转载 作者:行者123 更新时间:2023-11-29 09:14:56 25 4
gpt4 key购买 nike

我被这个问题困扰了几个小时。这可能是一个快速的解决方案,但我的大脑现在过热了。好的,就在这里。

我有 Session 和 SessionType 模型,它们之间具有多对多关系,如下所示。

class Session < ActiveRecord::Base
...
has_and_belongs_to_many :session_types
...
end

class SessionType < ActiveRecord::Base
...
has_and_belongs_to_many :sessions
...
end

我想要的是获得一个不包含任何特定 session_type 的 session ,例如,

Session.find(:all, :joins => [:session_types], :conditions => ["session_types.id <> 44"])

它对我不起作用,因为由于多对多关系的性质,上述查询仍会为我提供在许多关联中具有 session_types.id“44”的 session 。

下面的 mysql 代码也不能正常工作。

select sessions.* from sessions
INNER JOIN `session_types_sessions` ON `session_types_sessions`.session_id = `sessions`.id
WHERE ( session_types_sessions.session_type_id NOT IN (44))
GROUP BY sessions.id

任何帮助将不胜感激。

谢谢。

最佳答案

首先选择类型为 44 的 session :

session_types_44 = Session.find(:all, :joins => :session_types, 
:conditions => { :"session_types.id" => 44 }).uniq

并选择不属于上述范围的 session :

sessions_without_type_44 = Session.find(:all, 
:conditions => "id NOT IN (#{session_types_44.join(",")})")

您需要小心这一点,因为如果 session_types_44 是空数组,您将收到 SQL 错误。

并回答您的第二个问题:

do you know how I could change the SQL to filter like "get me sessions which have session_type_id '43', but they must NOT have '44'

sessions_without_type_44 获取结果并使用它。首先选择 SessionType 为 43,然后通过关联获取属于该 SessionType 的所有 session ,并且它们的 id 位于 sessions_without_type_44 中:

SessionType.find(43).sessions.all(:conditions => { 
:id => sessions_without_type_44 })

关于mysql - 如何从 Rails 2 中不包含特定项目的多对多关系中选择特定记录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4440680/

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