【问题标题】:How to whereDate, whereMonth a variable?怎么给whereDate, whereMonth一个变量呢?
【发布时间】:2020-01-17 19:26:53
【问题描述】:

我想只使用一个变量来显示总付款本月的总付款

控制器

$payments = Payment::where('user_id', auth()->user()->id)->get();

return view('subscribers.payments', compact(['payments']));

查看

<label>Total payments</label>
<p>{{ $payments->sum('amount') }}</p>

<label>For this month</label>
<p>{{ $payments->whereMonth('created_at', now()->month)->sum('amount') }}</p>

实际上显示了总付款。但是“本月”它不起作用,并在下面返回一个错误:

方法 Illuminate\Database\Eloquent\Collection::whereMonth 不存在。


有人可以告诉我哪里出错了吗?以及实现这一目标的正确方法?

【问题讨论】:

    标签: laravel eloquent laravel-5.8


    【解决方案1】:

    当您拥有超过一年的数据时,单独按月查询会不会在以后产生问题?我只会使用当月的开始。

    <p>{{ $payments->where('created_at', '>=', now()->startOfMonth())->sum('amount') }}</p>
    

    【讨论】:

    • 感谢您的回复先生。最后一个问题,now()-&gt;startOfMonth()now()-&gt;month 有什么区别,很好奇?
    • now()-&gt;startOfMonth() 是当月最早日期(2019-09-01 00:00:00)的 Carbon 实例。 now()-&gt;month 是当前月份 (9) 的整数表示形式。
    • 啊这就是为什么它不能直接比较created_at,因为它是一个整数,谢谢解释得很好
    【解决方案2】:

    所以很遗憾,whereMonth 仅适用于查询生成器。你可以filter检索后的项目:

    $payments->filter(function ($payment) {
        return $payment->created_at->month == now()->month;
    })->sum('amount') 
    

    【讨论】:

    • 感谢您的回复先生。它返回一个错误Object of class Illuminate\Support\Carbon could not be converted to int
    • 或许可以试试created_at-&gt;month
    • 它正在工作,先生,谢谢。但我会选择少编码的。
    猜你喜欢
    • 2021-04-28
    • 1970-01-01
    • 1970-01-01
    • 2014-05-23
    • 1970-01-01
    • 2013-04-26
    • 2012-02-01
    • 1970-01-01
    • 2021-04-30
    相关资源
    最近更新 更多