在 Rails 中,类似于 Laravel 中的 orWhereHas 方法,可以使用 or 关键字来连接多个 where 条件。

假设有两个模型,Product 和 Sku,Product 拥有多个 Sku。想要查询包含特定关键字的 Product,并且关联的 Sku 中的 title 或 description 也包含该关键字,可以使用以下方法:

Product.joins(:skus).where("products.title LIKE ? OR products.description LIKE ? OR skus.title LIKE ? OR skus.description LIKE ?", "%#{keyword}%", "%#{keyword}%", "%#{keyword}%", "%#{keyword}%")

这里的关键字为 keyword,使用 % 进行模糊匹配。使用 joins 方法连接两个模型,并使用 where 方法添加多个条件,使用 OR 关键字连接不同的条件。

Rails 中实现类似 Laravel orWhereHas 的查询方法

原文地址: https://www.cveoy.top/t/topic/pWwM 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录