Browse Source

修复搜索功能,让服务器端同时搜索多个字段

pull/11/head
徐飞洋 2 months ago
parent
commit
db9acaed26
  1. 102
      pages/index/index.js
  2. 10
      server-example/server-mysql.js
  3. 5
      utils/api.js

102
pages/index/index.js

@ -463,7 +463,8 @@ Page({
lastDataTimestamp: 0 lastDataTimestamp: 0
}); });
// 优先查询published状态的商品 // 优先查询published状态的商品,如果有搜索关键词则同时查询sold_out状态
const statusList = currentKeyword ? ['published', 'sold_out'] : ['published'];
const apiParams = { const apiParams = {
timestamp: timestamp, timestamp: timestamp,
viewMode: 'shopping', viewMode: 'shopping',
@ -475,7 +476,7 @@ Page({
if (currentCategory) { if (currentCategory) {
apiParams.category = currentCategory apiParams.category = currentCategory
} }
API.getProductList(['published'], apiParams) API.getProductList(statusList, apiParams)
.then(res => { .then(res => {
this.setData({ isRefreshing: false }) this.setData({ isRefreshing: false })
@ -764,10 +765,12 @@ Page({
} }
const filteredGoods = this.applyFilters(updatedGoods, false) const filteredGoods = this.applyFilters(updatedGoods, false)
const groupedGoods = this.groupGoodsForStaggeredLayout(filteredGoods);
this.setData({ this.setData({
goods: updatedGoods, goods: updatedGoods,
filteredGoods: filteredGoods, filteredGoods: filteredGoods,
groupedGoods: groupedGoods,
loadingMore: false, loadingMore: false,
isLoading: false, isLoading: false,
isRefreshing: false, isRefreshing: false,
@ -830,6 +833,7 @@ Page({
const updatedGoods = [...existingGoods, ...uniqueNewGoods] const updatedGoods = [...existingGoods, ...uniqueNewGoods]
const filteredGoods = this.applyFilters(updatedGoods, false) const filteredGoods = this.applyFilters(updatedGoods, false)
const groupedGoods = this.groupGoodsForStaggeredLayout(filteredGoods);
const currentCategory = this.data.selectedCategory === '全部' ? '' : this.data.selectedCategory; const currentCategory = this.data.selectedCategory === '全部' ? '' : this.data.selectedCategory;
const currentKeyword = this.data.searchKeyword; const currentKeyword = this.data.searchKeyword;
@ -838,6 +842,7 @@ Page({
this.setData({ this.setData({
goods: updatedGoods, goods: updatedGoods,
filteredGoods: filteredGoods, filteredGoods: filteredGoods,
groupedGoods: groupedGoods,
loadingMore: false, loadingMore: false,
isLoading: false, isLoading: false,
page: this.data.page + 1, page: this.data.page + 1,
@ -929,6 +934,10 @@ Page({
return return
} }
console.log('loadGoods - 开始加载商品,isLoadMore:', isLoadMore, 'forceRefresh:', forceRefresh);
console.log('loadGoods - 当前搜索关键词:', this.data.searchKeyword);
console.log('loadGoods - 当前分类:', this.data.selectedCategory);
const currentCategory = this.data.selectedCategory === '全部' ? '' : this.data.selectedCategory; const currentCategory = this.data.selectedCategory === '全部' ? '' : this.data.selectedCategory;
const currentKeyword = this.data.searchKeyword; const currentKeyword = this.data.searchKeyword;
const cacheKey = `${currentCategory}_${currentKeyword}`; const cacheKey = `${currentCategory}_${currentKeyword}`;
@ -962,7 +971,7 @@ Page({
const page = isLoadMore ? this.data.page : 1 const page = isLoadMore ? this.data.page : 1
const pageSize = this.data.pageSize; const pageSize = this.data.pageSize;
// 优先查询published状态的商品 // 构建API请求参数
const apiParams = { const apiParams = {
timestamp: timestamp, timestamp: timestamp,
viewMode: 'shopping', viewMode: 'shopping',
@ -974,11 +983,18 @@ Page({
if (currentCategory) { if (currentCategory) {
apiParams.category = currentCategory apiParams.category = currentCategory
} }
API.getProductList(['published'], apiParams)
console.log('loadGoods - API请求参数:', apiParams);
// 在搜索时同时查询published和sold_out状态的商品,否则只查询published
const statusList = this.data.searchKeyword ? ['published', 'sold_out'] : ['published'];
console.log('loadGoods - 查询状态列表:', statusList);
API.getProductList(statusList, apiParams)
.then(res => { .then(res => {
wx.hideLoading(); wx.hideLoading();
console.log('===== published状态查询结果 ====='); console.log(`===== ${statusList.join(', ')}状态查询结果 =====`);
console.log('res.success:', res.success); console.log('res.success:', res.success);
console.log('res.products:', res.products); console.log('res.products:', res.products);
console.log('res.products.length:', res.products ? res.products.length : 'undefined'); console.log('res.products.length:', res.products ? res.products.length : 'undefined');
@ -1219,10 +1235,12 @@ Page({
// 应用筛选条件 // 应用筛选条件
const filteredGoods = this.applyFilters(processedGoods, false); const filteredGoods = this.applyFilters(processedGoods, false);
const groupedGoods = this.groupGoodsForStaggeredLayout(filteredGoods);
this.setData({ this.setData({
goods: processedGoods, goods: processedGoods,
filteredGoods: filteredGoods, filteredGoods: filteredGoods,
groupedGoods: groupedGoods,
loadingMore: false, loadingMore: false,
isLoading: false, isLoading: false,
isRefreshing: false, // 确保下拉刷新状态被重置 isRefreshing: false, // 确保下拉刷新状态被重置
@ -1280,31 +1298,59 @@ Page({
applyFilters: function(goods, shouldSort = true) { applyFilters: function(goods, shouldSort = true) {
let filtered = [...goods] let filtered = [...goods]
console.log('applyFilters - 开始过滤,原始商品数量:', goods.length, '关键词:', this.data.searchKeyword);
if (this.data.selectedCategory !== '全部') { if (this.data.selectedCategory !== '全部') {
const category = this.data.selectedCategory const category = this.data.selectedCategory
filtered = filtered.filter(item => item.isAd || (item.category === category)) filtered = filtered.filter(item => item.isAd || (item.category === category))
console.log('applyFilters - 分类过滤后数量:', filtered.length);
} }
if (this.data.searchKeyword) { if (this.data.searchKeyword) {
const keyword = this.data.searchKeyword.toLowerCase() const keyword = this.data.searchKeyword.toLowerCase()
const originalLength = filtered.length; const originalLength = filtered.length;
console.log('applyFilters - 搜索关键词:', keyword, '过滤前数量:', originalLength);
// 记录每个商品的匹配情况
filtered = filtered.filter(item => { filtered = filtered.filter(item => {
const nameMatch = (item.name || '').toLowerCase().includes(keyword); const nameMatch = (item.name || '').toLowerCase().includes(keyword);
const productNameMatch = (item.productName || '').toLowerCase().includes(keyword); const productNameMatch = (item.productName || '').toLowerCase().includes(keyword);
const specMatch = (item.specification || item.spec || '').toLowerCase().includes(keyword); const specification = (item.specification || item.spec || '').toLowerCase();
const specMatch = specification.includes(keyword);
const regionMatch = (item.region || '').toLowerCase().includes(keyword); const regionMatch = (item.region || '').toLowerCase().includes(keyword);
const grossWeightMatch = (item.grossWeight || '').toLowerCase().includes(keyword); const grossWeightMatch = (item.grossWeight || '').toLowerCase().includes(keyword);
const yolkMatch = (item.yolk || '').toLowerCase().includes(keyword); const yolkMatch = (item.yolk || '').toLowerCase().includes(keyword);
const match = item.isAd || nameMatch || productNameMatch || specMatch || regionMatch || grossWeightMatch || yolkMatch; const match = item.isAd || nameMatch || productNameMatch || specMatch || regionMatch || grossWeightMatch || yolkMatch;
if (!match && originalLength <= 5) { // 详细日志,记录每个商品的匹配字段
// 只为小数据集打印详细信息 if (originalLength <= 20 || keyword === '41' || keyword === '43-44') { // 增加特定关键词的日志记录
console.log('商品未匹配:', item.name); console.log('商品匹配详情:', {
name: item.name,
productId: item.productId || item.id,
keyword: keyword,
name: item.name,
productName: item.productName,
specification: item.specification,
spec: item.spec,
formattedSpecification: specification,
region: item.region,
grossWeight: item.grossWeight,
yolk: item.yolk,
nameMatch: nameMatch,
productNameMatch: productNameMatch,
specMatch: specMatch,
regionMatch: regionMatch,
grossWeightMatch: grossWeightMatch,
yolkMatch: yolkMatch,
match: match
});
} }
return match; return match;
}) })
console.log('applyFilters - 搜索过滤后数量:', filtered.length);
} }
if (this.data.selectedRegion !== '全国') { if (this.data.selectedRegion !== '全国') {
@ -1480,12 +1526,42 @@ Page({
app.globalData.showTabBar = true; app.globalData.showTabBar = true;
} }
const filteredGoods = this.applyFilters(this.data.goods, false) console.log('searchGoods - 开始搜索,关键词:', this.data.searchKeyword);
const groupedGoods = this.groupGoodsForStaggeredLayout(filteredGoods) console.log('searchGoods - 本地已有商品数量:', this.data.goods.length);
// 先对本地已加载的商品进行过滤
const filteredGoods = this.applyFilters(this.data.goods, false);
console.log('searchGoods - 本地过滤结果数量:', filteredGoods.length);
// 如果本地过滤结果不足,或者没有匹配的商品,则重新加载数据
if (filteredGoods.length < 3 && this.data.searchKeyword) {
console.log('searchGoods - 本地过滤结果不足3个,将重新加载数据');
this.setData({
page: 1,
hasMoreData: true,
goods: [],
filteredGoods: [],
loadingMore: false,
// 清除相关缓存以获取最新数据
lastDataTimestamp: 0,
categoryQueryCache: {},
isQueryingSoldOut: false,
publishedHasMore: true,
soldOutPage: 1
}, () => {
console.log('searchGoods:本地商品不足,重新加载数据,搜索关键词:', this.data.searchKeyword);
this.loadGoods(false, true); // 第二个参数true表示强制刷新
});
} else {
// 本地商品足够,直接使用本地过滤结果
console.log('searchGoods:使用本地商品过滤结果,数量:', filteredGoods.length);
const groupedGoods = this.groupGoodsForStaggeredLayout(filteredGoods);
this.setData({ this.setData({
filteredGoods: filteredGoods, filteredGoods: filteredGoods,
groupedGoods: groupedGoods, groupedGoods: groupedGoods
}) });
}
}, },
// 切换地区选择器 // 切换地区选择器

10
server-example/server-mysql.js

@ -1959,9 +1959,15 @@ app.post('/api/product/list', async (req, res) => {
console.log(`构建的完整查询条件:`, JSON.stringify(where, null, 2)); console.log(`构建的完整查询条件:`, JSON.stringify(where, null, 2));
// 关键词搜索 // 关键词搜索 - 同时搜索多个字段
if (keyword) { if (keyword) {
where.productName = { [Sequelize.Op.like]: `%${keyword}%` }; where[Sequelize.Op.or] = [
{ productName: { [Sequelize.Op.like]: `%${keyword}%` } },
{ specification: { [Sequelize.Op.like]: `%${keyword}%` } },
{ region: { [Sequelize.Op.like]: `%${keyword}%` } },
{ grossWeight: { [Sequelize.Op.like]: `%${keyword}%` } },
{ yolk: { [Sequelize.Op.like]: `%${keyword}%` } }
];
} }
// 分类筛选 // 分类筛选

5
utils/api.js

@ -1516,11 +1516,16 @@ module.exports = {
// 如果options中包含keyword,则添加到请求数据中 // 如果options中包含keyword,则添加到请求数据中
if (options.keyword) { if (options.keyword) {
requestData.keyword = options.keyword; requestData.keyword = options.keyword;
console.log('API.getProductList - 添加搜索关键词:', options.keyword);
} else {
console.log('API.getProductList - 未指定搜索关键词');
} }
console.log('API.getProductList - 分页参数:', { page: page, pageSize: pageSize }); console.log('API.getProductList - 分页参数:', { page: page, pageSize: pageSize });
console.log('API.getProductList - 查询状态:', statusList); console.log('API.getProductList - 查询状态:', statusList);
console.log('API.getProductList - 请求数据:', requestData); console.log('API.getProductList - 请求数据:', requestData);
console.log('API.getProductList - 请求URL:', BASE_URL + '/api/product/list');
console.log('API.getProductList - 请求方法:', 'POST');
return request('/api/product/list', 'POST', requestData).then(data => { return request('/api/product/list', 'POST', requestData).then(data => {
// 添加详细的日志记录,查看服务器返回的完整数据 // 添加详细的日志记录,查看服务器返回的完整数据

Loading…
Cancel
Save