sql - Rails 和 SQL - 与数组、条目中的所有元素相关联
问题描述
我有这样的事情:
duplicates = ['a','b','c','d']
if duplicates.length > 4
Photo.includes(:tags).where('tags.name IN (?)',duplicates)
.references(:tags).limit(15).each do |f|
returned_array.push(f.id)
end
end
duplicatesPhoto
是与其他标签重复的标签数组
我想要的是获得Photo
包含重复数组中的所有标签的内容,但现在我得到的每一个都Photo
包含数组中的至少一个标签。
感谢您的回答:
我尝试了它们,有些东西开始起作用,但对我来说不太清楚,需要一些时间来执行。
今天我让它创建数组,比较它们,获取数组中存在超过 X 次的重复项,最后获得唯一的照片 id 数组。
解决方案
如果您想查找具有所有给定标签的照片,您只需要应用 GROUP 并使用 HAVING 为组设置条件:
class Photo
def self.with_tags(*names)
t = Tag.arel_table
joins(:tags)
.where(tags: { name: names })
.group(:id)
.having(t[:id].count.eq(tags.length)) # COUNT(tags.id) = ?
end
end
这有点像 WHERE 子句,但它适用于组。使用.gteq
( >=
) 代替.eq
将为您提供可以包含列表中所有标签但可能有更多标签的记录。
解决这个问题的一个更好的方法是使用一个更好的域模型,它首先不允许重复:
class Photo < ApplicationRecord
has_many :taggings
has_many :tags, through: :taggings
end
class Tag < ApplicationRecord
has_many :taggings
has_many :photos, through: :taggings
validates :name,
uniqueness: true,
presenece: true
end
class Tagging < ApplicationRecord
belongs_to :photo
belongs_to :tag
validates :tag_id,
uniqueness: { scope: :photo_id }
end
通过添加唯一索引tags.name
和复合索引,taggings.tag_id
无法taggings.photo_id
创建重复项。
推荐阅读
- android - 滑动删除,背景上的涟漪效果
- c# - 如何将进度条与进程同步
- sql - 仅选择开始的名称,例如 customer1 , customer2 .... 不是 customer
- html - 如何在 Vuetify 中使 App 内容可滚动?
- javascript - console.log 如何将 javascript 日期对象转换为人类可读格式
- reactjs - 导航栏显示不正确
- python - 如何将多个csv文件中的行复制到熊猫中的新文件中?
- vim - Vim 如何从用户定义的命令中自动返回
- javascript - 处理 SVG 并填充特定区域
- javascript - 等待 aws lambda 函数中的 forEach 循环