【问题标题】:Adonis Lucid ORM: How do I change the datetime to a date only and then use the .distinct()Adonis Lucid ORM:如何将日期时间更改为仅日期,然后使用 .distinct()
【发布时间】:2020-06-17 07:46:04
【问题描述】:

我有一个名为 Orders 的表

这是该表的示例值:

[
  {
     id: 1,
     delivery_date: 2020-06-01 00:00:00,
     quantity: 2
  },
  {
     id: 2,
     delivery_date: 2020-06-01 01:00:00,
     quantity: 2
  },
]

我现在查询这个

...
await Order
      .query()
      .select('delivery_date')
      .distinct('delivery_date')
      .fetch()

.distinct() 不起作用,因为时间不一样,所以我的问题是,即使时间不一样且日期相同,我如何使用 distinct 来工作?而且我还需要只返回日期,没有时间

【问题讨论】:

    标签: node.js postgresql knex.js adonis.js


    【解决方案1】:

    所以我所做的只是将日期和时间分开。根据项目要求,我认为这对我来说是最好的解决方案,不知道为什么,但阿多尼斯仍在增加我约会的时间,我认为这是幕后的时刻,所以要解决这个问题;

    你必须让 Adonis 知道你的列是一个日期,方法是在你的模型上添加这个,然后在那个数组中添加你的列名:

    static get dates () {
        return super.dates.concat(['delivery_date'])
    }
    

    之后我们需要在使用castDate显示数据时格式化该列

    static castDates(field, value) {
        if (field === 'delivery_date') {
          return value.format('YYYY-MM-DD')
        }
    
        return super.formatDates(field, value)
    }
    

    另请注意,您必须致电 .fetch() 才能工作

    所有这些都在文档中: https://adonisjs.com/docs/4.1/lucid#_dates

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-26
      • 1970-01-01
      • 1970-01-01
      • 2020-12-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多