【问题标题】:Laravel - method whereDate does not existLaravel - 方法 whereDate 不存在
【发布时间】:2019-08-06 20:08:46
【问题描述】:

所以在这个项目中,我的主页只显示当天发布的帖子。现在我需要那天的价格总和,为此我将它添加到我的价格总和代码中

在我的home.blade.php 中求总价:

<tfoot>
<tr>
    <th>UKUPAN IZNOS:&nbsp;&nbsp;{{ Auth::user()->posts->whereDate('created_at','=',$date)->sum('cijena') }}&euro;</th>
    <th>KARTICA:&nbsp;&nbsp;{{ Auth::user()->posts->where('placanje', 'Kartica')->whereDate('created_at','=',$date)->sum('cijena')}}&euro;</th>
    <th>GOTOVINA:&nbsp;&nbsp;{{ Auth::user()->posts->where('placanje', 'Gotovina')->whereDate('created_at','=',$date)->sum('cijena')}}&euro;</th>
    <th>VIRMAN:&nbsp;&nbsp;{{ Auth::user()->posts->where('placanje', 'Virman')->whereDate('created_at','=',$date)->sum('cijena')}}&euro;</th>
    <th>NK:&nbsp;&nbsp;{{ Auth::user()->posts->where('placanje', 'NK')->whereDate('created_at','=',$date)->sum('cijena')}}&euro;</th>
</tr>
</tfoot>

这个whereDate 方法来自我的HomeController,这里是:

public function index()
{
    $date = new Carbon(request('date'));

    $posts = Post::where('user_id', Auth::id())
            ->whereDate('created_at','=',$date)
            ->orderBy('created_at', 'DESC')
            ->paginate(30); //add {{ $posts->links() }} if paginate is enabled
    return view('home', compact('date', $date))->with('posts', $posts);
}

而我在web.php 的路线是:

Route::get('/home', 'HomeController@index')->name('home');

它返回给我的只是那个方法 whereDate 不存在。任何想法如何解决这个问题?

【问题讨论】:

  • 你认为错误是你忘记了每个-&gt;posts后面的括号:你应该使用Auth::user()-&gt;posts()-&gt;...
  • 要获取用户ID,请尝试Auth::user()-&gt;id
  • 是的,我忘了括号..这就是你恐慌时得到的..谢谢老兄。如果你能帮助我,我还有一个问题,我应该发布一个新问题还是我们可以在这里做?

标签: php laravel sum


【解决方案1】:

在您看来,您使用以下几行:

Auth::user()->posts->where...

考虑Auth::user()-&gt;posts 返回用户帖子collection,但Auth::user()-&gt;posts() 返回query builder 实例。

幸运的是,laravel collection 定义了 where() 方法,但它没有 whereDate() 方法,而是在 query builder 上定义的,所以在您看来,您必须使用这一行:

Auth::user()->posts()->whereDate('created_at','=',$date)->sum('cijena')

【讨论】:

  • 我修好了,非常感谢您抽出宝贵时间向我解释!
  • 我还有一个问题,我应该发一个新的问题帖子吗?
  • 这样更好,所以我们将把这个问题保持干净
  • 我同意,我马上再提一个问题!
  • 哎呀,我要等第二题,90分钟就一题你懂的……
猜你喜欢
  • 1970-01-01
  • 2018-02-07
  • 1970-01-01
  • 1970-01-01
  • 2019-05-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多