php - Laravel 查询 - SQL : Get records start new period today

标签 php mysql laravel laravel-query-builder

我陷入了 Laravel 查询。请看一下,让我知道任何线索或解决方案。 谢谢。

这是我的问题。

现在:2019-12-20。

我有一个模型People,其表格如下:

[
  {
    id: 1,
    type: 'employee',
    created_at: '2019-11-20',
  },
  {
    id: 2,
    type: 'employee',
    created_at: '2019-09-20',
  },
  {
    id: 3,
    type: 'employee',
    created_at: '2019-11-25',
  },
  {
    id: 4,
    type: 'ceo',
    created_at: '2019-11-20',
  },
  {
    id: 5,
    type: 'cfo',
    created_at: '2019-11-27',
  },
]

我必须每月恰好第 30 天(周期为 30 天)支付员工工资。

所以我的想法是获取记录:

  • 类型为employee
  • (现在 - 创建时间)% 30 = 0。

这是我到目前为止的代码:

$people = People::where('type', 'employee')->get();

foreach ($people as $key => $person) {
  $diff_in_days = Carbon::parse($person->created_at)->diffInDays(Carbon::now()) % 30;

  if ($diff_in_days === 0) {
    // paid for this person.
  }
}

我得到了结果:

[
  {
    id: 1,
    type: 'employee',
    created_at: '2019-11-20',
  },
  {
    id: 2,
    type: 'employee',
    created_at: '2019-09-20',
  },
]

我想知道有什么方法可以在第一个查询中获取适合 created_at 的记录。

我想它可能看起来像这样。

$people = People::where('type', 'employee')
                -> // some codes to compare: (now - created) % 30 === 0
                ->get();

foreach ($people as $key => $person) {
  // paid for this person.
}

谢谢大家。

最佳答案

你可以尝试 -

->whereRaw('DATEDIFF(now(), created_at) = 30')

DATEDIFF()

对于评论中的其他条件 -

DATEDIFF(NOW(), created_at) > 60

DATEDIFF(NOW(), created_at) > 90

DATEDIFF(NOW(), created_at) > 60 AND DATEDIFF(NOW(), created_at) <= 90

关于php - Laravel 查询 - SQL : Get records start new period today,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59419695/

相关文章:

php - 停止动态下拉列表中的重复行

php - 使用 wamp 服务器,数据未从 php 代码插入到 mysql 数据库中

php - 用于将多个值插入 HTML 表单上的单独行的数据库设计

用于复杂逻辑的 SQL 查询 (pl/sql)

mysql - 如何在 MySQL 中创建复合自引用外键?

php - 如何使用 Ajax 获取 URL 的标题、描述、image_url,就像在 Facebook 上共享链接一样

mysql - 将字母数字值插入 varchar 类型列

php - 如何从 laravel 中给定的 lat long 获得附近的法院?

php - 如何在laravel 5.5的s3存储桶中上传图像

php - Ardent 模型在保存后无法验证