我具有从数据库中选择商店及其产品的功能:
def create_unique_shop_query_no_keyword(categories, shop_ids) do
products_shops_categories = from p in Product,
join: ps in ProductShop, on: p.id == ps.p_id,
join: s in Shop, on: s.id == ps.s_id,
join: pc in ProductCategory, on: p.id == pc.p_id,
join: c in Subcategory, on: c.id == pc.c_id,
distinct: s.id,
where: c.id in ^categories,
where: s.id in ^shop_ids,
group_by: [s.id, s.name],
select: %{products: fragment(
"json_agg( DISTINCT (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)) AS products",
p.id,
p.name,
p.brand,
p.description,
p.image,
p.rating,
p.number_of_votes,
ps.not_in_shop_count,
ps.is_in_shop_count,
ps.price,
p.not_vegan_count,
p.vegan_count),
shop: fragment(
"json_agg( DISTINCT (?, ?, ST_X(?), ST_Y(?), ?, ?, ?, ?, ?)) AS shop",
s.id,
s.name,
s.point,
s.point,
s.place_id,
s.street,
s.suburb,
s.city,
s.street_number
)
}
end
我有另一个功能相同的功能,但是将关键字添加到混音中,该关键字检查产品名称或产品品牌中是否包含关键字(不一定是完整的单词:
def create_unique_shop_query(keyword, categories, shop_ids) do
products_shops_categories = from p in Product,
join: ps in ProductShop, on: p.id == ps.p_id,
join: s in Shop, on: s.id == ps.s_id,
join: pc in ProductCategory, on: p.id == pc.p_id,
join: c in Subcategory, on: c.id == pc.c_id,
distinct: s.id,
where: c.id in ^categories,
where: s.id in ^shop_ids,
where: like(p.name, ^("%#{keyword}%")),
or_where: like(p.brand, ^("%#{keyword}%")),
group_by: [s.id, s.name],
select: %{products: fragment(
"json_agg( DISTINCT (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)) AS products",
p.id,
p.name,
p.brand,
p.description,
p.image,
p.rating,
p.number_of_votes,
ps.not_in_shop_count,
ps.is_in_shop_count,
ps.price,
p.not_vegan_count,
p.vegan_count),
shop: fragment(
"json_agg( DISTINCT (?, ?, ST_X(?), ST_Y(?), ?, ?, ?, ?, ?)) AS shop",
s.id,
s.name,
s.point,
s.point,
s.place_id,
s.street,
s.suburb,
s.city,
s.street_number
)
}
end
顶部功能,没有关键字,按预期方式工作。但是在具有关键字的函数中,结果包含商店ID(s.id
)不在shop_ids
中的商店。为什么会这样?
您有一个or_where
,因此您的查询条件本质上是....
(c.id in categories) and (s.id in shop_ids) and (p.name like keyword) or (p.brand like keyword)