【问题标题】:Laravel fetch data where carbon last monthLaravel 获取上个月碳含量的数据
【发布时间】:2017-01-21 07:45:05
【问题描述】:

我正在尝试从日期等于上个月日期范围的数据中获取第一个结果。

这是我的数据库内容的示例 -

id  date_recorded
1   2016-07-22 15:21:33
2   2016-08-13 12:22:22
3   2016-07-06 12:22:22
4   2016-09-12 12:45:22

这是我获取第二个结果(上个月的最新结果)的查询。

$seoScoreLastMonth = Manual::where('account_id', Auth::user()->account)
->where('date_recorded', '>=', Carbon::now()->subMonth())
->orderBy('date_recorded', 'desc')
->pluck('seo_score')
->first();

返回的结果为null,这是因为id在数据库中的第一个结果与日期不匹配?

【问题讨论】:

  • 只是为了确定,您的第一个 where 语句是否匹配任何信息?
  • 是的,我尝试了多种组合,并且一切正常,我可以按正确的顺序转储结果。只有当我说 date->subMonth 似乎抛出它并返回第一个值时
  • 好的,你使用的是哪个版本的 Laravel?我问是因为我在本地 Laravel 5.3 应用程序中输入 App\Models\User::where('created_at', '>=', Carbon\Carbon::now()->subMonth())->orderBy('created_at')->pluck('first_name')->first(); 并返回数据。
  • 尝试使用 Carbon\Carbon::now()->subMonth()->toDateTimeString() 代替 Carbon\Carbon::now()->subMonth()
  • 另一个问题:manuals 表中是否存在seo_score 字段?当我试图提取一个不存在的字段时,它返回 null。

标签: php mysql laravel eloquent php-carbon


【解决方案1】:

这个月我需要。这是我的查询。我认为您可以根据需要对其进行修改

$start = new Carbon('first day of this month');
$start = $start->startOfMonth()->format('Y-m-d H:i:s'); // startOfMonth for 00:00 time

您的查询..->where('date_recorded','>',$start)..

Carbon - get first day of monthenter link description here的帮助下

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-13
    • 2021-10-10
    相关资源
    最近更新 更多