如何从 Rails 2 中不包含特定项目的多对多关系中选择特定记录?
我被这个问题困扰了几个小时。这可能是一个快速的解决方案,但我的大脑现在过热了。好的,就在这里。
我有 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.find(:all, :joins => [:session_types], :conditions => ["session_types.id <> 44"])
它对我不起作用,因为上面的查询仍然会给我在许多关联中具有 session_types.id“44”的会话由于多对多关系的本质。
另外下面的 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
任何帮助将不胜感激。
谢谢。
I am stuck with this for a couple of hours. It could be a quick solution but my brain is overheated now. Ok here it is.
I have Session and SessionType models which have many-to-many relationships to each other as follows.
class Session < ActiveRecord::Base
...
has_and_belongs_to_many :session_types
...
end
class SessionType < ActiveRecord::Base
...
has_and_belongs_to_many :sessions
...
end
What I want is to get a session which doesn't contain any specific session_type, eg.,
Session.find(:all, :joins => [:session_types], :conditions => ["session_types.id <> 44"])
It doesn't work for me since the above query will still give me the sessions which have session_types.id "44" in many of its associations because of the nature of many-to-many relationships.
Also the following mysql code doesn't work as well.
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
Any help will be appreciated.
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
首先选择类型为 44 的会话:
并选择不属于上述类型的会话:
您需要小心,因为如果
session_types_44
是空数组,您将收到 SQL 错误。并回答您的第二问题:
从
sessions_without_type_44
获取结果并使用它。首先选择 SessionType使用 43 并通过关联获取属于该 SessionType 的所有会话,并且它们的 id 位于sessions_without_type_44
内:First select those sessions which are of type 44:
and select sessions which do not fall into the above:
You need to be careful with that because if
session_types_44
is empty array you will get SQL error.And to answer your second question:
Take the result from
sessions_without_type_44
and use it. First select SessionType with 43 and through association get all sessions which belong to that SessionType and their ids are within thesessions_without_type_44
:试试这个:
Try this:
试试这个:
include
选项使用 LEFT JOIN,因此该查询将起作用。Try this:
The
include
option uses LEFT JOIN hence this query will work.