В приведенном ниже коде мне пришлось получить изображения продуктов магазинов и их идентификаторы вместе с некоторыми другими данными, такими как рейтинги, количество и т. Д.
In below code I had to retrieve a shop products images and its ids.
exports.filterShopListings = async (data) => {
return Db.sequelize.query("SELECT productImages, S.shopId, S.currency, S.mainImage, S.mainImageThumb, S.coverImage, S.coverImageThumb, S.name, S.location, S.approved, S.locationLatitude, CONCAT('"+process.env.QR_URL+"',S.qrCode) as qrCode, S.locationLongitude, COALESCE(productCount,0) as productCount, COALESCE(ratingCount,0) as ratingCount, COALESCE(ROUND(UR.ratingAvg,1) ,0) as ratings, COALESCE(shopFollowing,0) as followingCount FROM shops as S JOIN users U ON (U.userId=S.userId AND U.blocked='0') LEFT JOIN ( SELECT COUNT(*) as productCount, shopId, GROUP_CONCAT(mainImageThumb,'--',shopProductId) as productImages FROM shopProducts WHERE shopProducts.deleted='0' AND shopProducts.blocked='0' GROUP BY shopId) SP ON (SP.shopId=S.shopId) LEFT JOIN ( SELECT COUNT(*) as ratingCount, AVG(ratings) as ratingAvg, shopId FROM userRatings WHERE userRatings.blocked='0' AND userRatings.deleted='0' GROUP BY shopId ) UR ON (UR.shopId=S.shopId) LEFT JOIN ( SELECT COUNT(*) as shopFollowing, shopId FROM shopFollowings GROUP BY shopId) SF ON (SF.shopId=S.shopId) WHERE "+data.whereString+" HAVING "+data.havingString+" ORDER BY "+data.orderingParam+" "+data.orderingSort+" LIMIT "+data.skip+", "+data.take+" ",{ type: Sequelize.QueryTypes.SELECT})
.then( (shops) => {
shops = JSON.parse(JSON.stringify(shops));
shops.forEach( (shop) => {
//shop.productImagesTemp = shop.productImages;
shop.productImages = shopImagesFunc(shop.productImages);
});
return shops;
});
};
и код ShopImagesFunc -
var shopImagesFunc = (productImages) => {
if(productImages ==null)
return [];
var images = (productImages.split(",").filter(Boolean));
var newImages = [];
images.forEach(image => {
let temp = image.split("--").filter(Boolean);
newImages.push({
shopProductId: parseInt(temp[1]),
mainImage: temp[0],
});
});
return newImages;
};
SQL-запрос немного сложен, но было бы очень полезно создать общую функцию для форматирования в требуемый вывод.