我陷入了 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(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/