方法whereYear不存在

时间:2018-01-20 10:14:14

标签: php laravel-5

所以我在我的网站上按年或月搜索新闻,因此我使用了whereYear方法,但出于某种原因,它的说法methon whereYear不存在。

  $news = News::paginate(6);


    if ($year != null && $month != null){

        $news->whereYear('created_at','=',$year)->whereMonth('created_at','=',$month)->get();

    }
    if ($year != null && $month == null){
        $news->whereYear('created_at','=',$year)->get();

    }
    if ($year == null && $month != null){
        $news->whereMonth('created_at','=',$month)->get();
    }

我有laravel 5.5

1 个答案:

答案 0 :(得分:2)

您正试图在您的分页实例上使用Query Builder中的方法。

paginate来电移至最后,并使用::query()启动查询。

$query = News::query(); 

if ($year != null && $month != null){
    $query->whereYear('created_at','=',$year)->whereMonth('created_at','=',$month);
}

if ($year != null && $month == null){
    $query->whereYear('created_at','=',$year);
}

if ($year == null && $month != null){
    $query->whereMonth('created_at','=',$month);
}

$news = $query->paginate(6);