在rails 5中的LIKE查询无法正常工作

时间:2022-04-25 11:18:01

Using this :

使用这个:

.. .where("field1 IN(?) AND field2 LIKE(?) AND field3 LIKE(?) ", params[:array_for_field1], "%#{params[:array_for_field2]}%", "%#{params[:array_for_field3]}%")

I'm getting this :

我明白这个:

SELECT `table`.* FROM `table` WHERE(field1 IN('value1','value2','value3') AND field2 LIKE('%[\"value1\", \"value2\"]%') AND field3 LIKE('%[\"value1\"]%') )

I would like to know where's the mistake, for field1 works, but the "LIKE Query" part using % is not, the params comes from a checkboxes form. thank you

我想知道哪里出错了,因为field1有效,但是使用%的“LIKE Query”部分不是,params来自一个复选框形式。谢谢

2 个解决方案

#1


0  

According to this response if you are using Postgres you can try something like this :

根据这个回复如果你使用Postgres你可以尝试这样的事情:

field2_ilike_params = params[:array_for_field2].map { |p| "%p%" }
field3_ilike_params = params[:array_for_field3].map { |p| "%p%" }
Model.where(field1: params[:array_for_field1]).where("field2 ILIKE ANY ( array[?] ) AND field3 ILIKE ANY ( array[?] )", field2_ilike_params, field3_ilike_params)

#2


1  

I end up using this solution with REGEX, it works as I needed.

我最终使用这个解决方案与REGEX,它按我的需要工作。

.where("field1 IN(?) AND field2 RLIKE(?) AND field3 RLIKE(?) ", params[:array_for_field1], params[:array_for_field2].join("|"), params[:array_for_field3].join("|"))

#1


0  

According to this response if you are using Postgres you can try something like this :

根据这个回复如果你使用Postgres你可以尝试这样的事情:

field2_ilike_params = params[:array_for_field2].map { |p| "%p%" }
field3_ilike_params = params[:array_for_field3].map { |p| "%p%" }
Model.where(field1: params[:array_for_field1]).where("field2 ILIKE ANY ( array[?] ) AND field3 ILIKE ANY ( array[?] )", field2_ilike_params, field3_ilike_params)

#2


1  

I end up using this solution with REGEX, it works as I needed.

我最终使用这个解决方案与REGEX,它按我的需要工作。

.where("field1 IN(?) AND field2 RLIKE(?) AND field3 RLIKE(?) ", params[:array_for_field1], params[:array_for_field2].join("|"), params[:array_for_field3].join("|"))