gpt4 book ai didi

mysql - 我可以在数据库中找到具有给定字符串数组但使用部分字符串的项目吗?

转载 作者:太空宇宙 更新时间:2023-11-03 11:22:15 24 4
gpt4 key购买 nike

我的模型 Product 带有 namecategory

种子:

Product.create(name: "apple", category: "food")
Product.create(name: "biogesic", category: "medicine")

和一个二维数组:

[[1, "tray of apple", 150.00], [1, "box of ballpen", 70.30]]

我需要的是获取数组中的字符串是否包含或在表/数据库上 Product

这是我的想法,但我迷路了:

isProduct = Product.where("name like ?", "%an apple%").first

"%apple%" 应该是 array 上的字符串,但对于该代码,它仅限于 1 个单词。

我不需要产品 id,如果它在 Product 表中,我就需要它。

最佳答案

在某种程度上,这可以通过 PostgreSQL 的正则表达式运算符 ~ 和/或 MySQL 的 REGEXP 来实现:

regex = array.flat_map { |_, sentence, _| sentence.split }.join('|')
Product.exists?(['name ~ ?', regex])
Product.exists?(['name REGEXP ?', regex])

产生:

SELECT 1 AS one FROM "products" WHERE (name ~ 'tray|of|apple|box|of|ballpen') LIMIT $1  [["LIMIT", 1]]

当它搜索句子tray of apple 和/或box of ballpen 中的每个单词时。

因此,如果您有这样的记录:

Product.new(name: 'tray of apple and box of ballpen')

它将覆盖查询并返回 true。

关于mysql - 我可以在数据库中找到具有给定字符串数组但使用部分字符串的项目吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58682104/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com