簡體   English   中英

在 createdAt 的 sequelize 中按月過濾

[英]Filter by month in sequelize from createdAt

我有這樣的原始查詢

SELECT trx.WarehouseId, pr.CategoryId, pr.id AS productId, ct.category_name, pr.product_name, pr.description, trx_items.price_per_item AS price, trx_items.quantity,
trx_items.price_per_item * trx_items.quantity AS total, wr.warehouse_name, trx_items.createdAt
FROM transactionitems AS trx_items
JOIN transactions AS trx ON trx.id = trx_items.TransactionId
JOIN products AS pr ON pr.id = trx_items.ProductId
JOIN categories AS ct ON ct.id = pr.CategoryId
JOIN warehouses as wr ON wr.id = trx.WarehouseId
WHERE MONTH(trx_items.createdAt) = 2;

它會在 2 月返回所有數據,所以我想將原始查詢轉換為 sequlize,但我不知道如何在 sequlize 中獲取月份。 我有這樣的續集代碼

 const { createdAt } = req.query
            if (createdAt) {
                const findDataFilter = await db.Transaction.findAndCountAll({
                    include: [
                        {
                            model: db.Warehouse,
                        },
                        {
                            model: db.TransactionItem,
                            include: [
                                {
                                    model: db.Product,
                                    include: [
                                        {
                                            model: db.Category,
                                        },
                                    ],
                                },
                            ],
                            required: true,
                            where: sequelize.fn(
                                "MONTH",
                                sequelize.col("createdAt")
                            ),
                        },
                    ],
                    
                })
                return res.status(200).json({
                    message: "Get data filtered",
                    data: findDataFilter.rows,
                    dataCount: findDataFilter.count,
                })
            }

它返回“on 子句中的列‘createdAt’不明確”。 我是 sequelize 的新手,所以我不知道使用什么方法。 如果我寫where: {createdAt}這什么都不返回

我想在表 TransactionItem 中按月過濾,但要使用 sequelize。

我認為createdAt存在於比transactionitems更多的表中,這就是錯誤是“列歧義”的原因。

您應該像這樣在列之前指定表格:

sequelize.fn(
  "MONTH",
  sequelize.col("TransactionItem.createdAt")
)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM