如何使用rails或sql通过has_many关联查询?

时间:2022-01-29 20:09:31
class Movie
  has_many :movie_genres
  has_many :genres, through: :movie_genres
end

I want find basically films that are not 'Short'.

我想找到基本上不是'短'的电影。

I tried joins(:genres).where('genres.name is not ?', 'Short'), but seems to be returning movies whose first genre isn't 'Short' instead.

我试过加入(:流派).where('genres.name不是?','短'),但似乎回归的电影的第一个类型不是'短'而是。

2 个解决方案

#1


1  

First you need to find out all movies which are having genre as 'Short' and then exclude those movies from final list. Try out something like following:

首先,您需要找出所有类型为“短”的电影,然后从最终列表中排除这些电影。尝试以下内容:

Movie.where.not(id: Movie.joins(:genres).where('genres.name = ?', 'Short').pluck(:id))

#2


0  

You can use where with not like below

您可以使用不在下面的地方

Movie.joins(:genres).where.not('genres.name = ?', 'Short')

#1


1  

First you need to find out all movies which are having genre as 'Short' and then exclude those movies from final list. Try out something like following:

首先,您需要找出所有类型为“短”的电影,然后从最终列表中排除这些电影。尝试以下内容:

Movie.where.not(id: Movie.joins(:genres).where('genres.name = ?', 'Short').pluck(:id))

#2


0  

You can use where with not like below

您可以使用不在下面的地方

Movie.joins(:genres).where.not('genres.name = ?', 'Short')