简体   繁体   English

Rails 5:如果结果与特定记录相关联,则查询将不包括在内

[英]Rails 5: Query which excludes results if they're associated with a specific record

I've got two models: Playlist and Item . 我有两个模型: PlaylistItem I want to build a query which returns all playlists except those which have an specific item. 我想建立一个查询,该查询返回除具有特定项目的播放列表以外的所有播放列表。

These are the models: 这些是模型:

class Playlist < ApplicationRecord
  has_many :items
end

class Item < ApplicationRecord
  belongs_to :playlist
end

This is a query which doesn't work since there could be playlists which have the specified item, but also several more, and if they have other items, they are included (which is what I don't want): 这是一个无效的查询,因为可能存在具有指定项目的播放列表,但还有多个列表,如果还有其他项目,则将它们包括在内(这是我不想要的):

Playlist.left_outer_joins(:items).where.not(items: { uid: id })

For the record, my DBMS is PostgreSQL 9.6 作为记录,我的DBMS是PostgreSQL 9.6

Probably this can be written in a better way but it should work: 也许可以用更好的方式编写它,但是它应该可以工作:

join_sql = Arel.sql(
  "LEFT OUTER JOIN items ON " \
  "(items.playlist_id = playlists.uid " \
  "AND items.some_id = '#{item.some_id}')"
)

Playlist.where(owner: owner)
        .joins(join_sql)
        .where(items: { playlist_id: nil })

The concept is similar to this one: https://stackoverflow.com/a/2686266 这个概念与此类似: https : //stackoverflow.com/a/2686266

I don't have a setup to quickly test this, but I think you can use a Rails ActiveRecord subquery: 我没有设置可以快速测试此设置,但是我认为您可以使用Rails ActiveRecord子查询:

Playlist.where.not(id: Item.select(:pl_id).where(id: id_to_exclude))

Here, pl_id is the name of the attribute in Item corresponding to the playlist Id. 在此, pl_idItem与播放列表ID对应的属性名称。 I'm also assuming that id is the primary key in each of your tables. 我还假设id是每个表中的主键。 This might be a compact way for a result, but may not be the most efficient from a query perspective. 这可能是一种紧凑的结果方法,但从查询角度来看可能不是最有效的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM