Sequel 模型过滤多对多关系
Sequel model filtering many-to-many relationships
这个问题最好通过一个例子来说明。我有 2 个 Sequel
模型,Artists
和 Genres
,通过连接器 table:
通过多对多关系连接
class Artist < Sequel::Model
many_to_many :genres,
left_key: :artist_id,
right_key: :genre_id,
join_table: :artists_genres
end
class Genres < Sequel::Model
many_to_many :artists,
left_key: :genre_id,
right_key: :artist_id,
join_table: :artists_genres
end
而木匠 table 看起来很简单:
CREATE TABLE `artists_genres` (`artist_id` integer, `genre_id` integer)
我想做的是过滤属于特定流派的所有艺术家。这在使用单一类型时效果很好:
some_genre = Genre[1]
Artists.dataset.where(:genres => some_genre).all
我的问题是试图获取属于某个流派集合的所有艺术家:
multiple_genres = Genre.where(:id => [1,2,4])
Artists.dataset.where(:genres => multiple_genres).all
这 returns 位艺术家属于 3 种类型(1、2 或 4)中的任何一种,而不是属于所有 3 种类型的艺术家。
通过模型查询或重写为数据集 join
调用 select 正确行的正确方法是什么?
正如@mudasobwa 在评论中提到的,您可以附加多个 where
方法
multiple_genres = Genre.where(id: [1, 2, 4])
result = Artists.dataset
multiple_genres.each { |g| result = result.where(genres: g) }
result.all
这个问题最好通过一个例子来说明。我有 2 个 Sequel
模型,Artists
和 Genres
,通过连接器 table:
class Artist < Sequel::Model
many_to_many :genres,
left_key: :artist_id,
right_key: :genre_id,
join_table: :artists_genres
end
class Genres < Sequel::Model
many_to_many :artists,
left_key: :genre_id,
right_key: :artist_id,
join_table: :artists_genres
end
而木匠 table 看起来很简单:
CREATE TABLE `artists_genres` (`artist_id` integer, `genre_id` integer)
我想做的是过滤属于特定流派的所有艺术家。这在使用单一类型时效果很好:
some_genre = Genre[1]
Artists.dataset.where(:genres => some_genre).all
我的问题是试图获取属于某个流派集合的所有艺术家:
multiple_genres = Genre.where(:id => [1,2,4])
Artists.dataset.where(:genres => multiple_genres).all
这 returns 位艺术家属于 3 种类型(1、2 或 4)中的任何一种,而不是属于所有 3 种类型的艺术家。
通过模型查询或重写为数据集 join
调用 select 正确行的正确方法是什么?
正如@mudasobwa 在评论中提到的,您可以附加多个 where
方法
multiple_genres = Genre.where(id: [1, 2, 4])
result = Artists.dataset
multiple_genres.each { |g| result = result.where(genres: g) }
result.all