2017-01-05 131 views
1

我试图查询我的NewsItem表的文章写在给定的月份/年。Laravel雄辩在哪里创建在

我传递的URL GET变量

'/news?filter=true&month=January 2017' 

在我的控制器我赶上变量,并试图在我的模式

if(Input::get('month')){ 
    $articles = NewsItem::where(DB::raw('created_at'),function($d){ 
     Carbon::parse($d->created_at)->format('F Y') = Input::get('month'); 
    })->get(); 
}; 

运行查询,但我得到以下错误

NewsController.php中的FatalErrorException第28行:无法使用方法 在写入con中返回值文字

我想知道更多关于功能元素的雄辩,有没有什么文章能引导我朝着正确的方向发展?

+0

我假设news_items表的created_at字段是日期时间字段? – Robert

回答

1

你的查询需要进行修改,这样

if (Input::get('month')) { 
    $articles = NewsItem::where('created_at', Carbon::parse(Input::get('month'))->format('F Y'))->get(); 
}; 

参考Laravel WhereEloquent 101更多信息

0

假设created_at是正常datetime场。

如果您需要从当月开始的所有文章,您可以结合使用一些不错的碳帮助器,因此在这种情况下不需要使用闭包。

例子:

// Garble or empty inputs will throw an Exception in Carbon 
try { 
    // this will create a Carbon object or Carbon will throw an exception 
    $date = Carbon::parse(request()->input('month')); 

    $articles = NewsItem::whereBetween('created_at', [ 
      $date->startOfMonth()->toDateTimeString(), 
      $date->endOfMonth()->toDateTimeString(), 
    ])->get(); 

} catch(\Exception $e) { 
    // gracefully handle Exception 
    dd($e->getMessage()); 
} 

因此,使用这里封闭在这里不需要。

如果你想看到如何使用它们的示例,请参阅Laravel query parameter grouping


一些附加实例闭包:

在你的情况,而不是之间使用,你也可以组2在这样的关闭:

// Garble or empty inputs will throw an Exception in Carbon 
try { 
    // this will create a Carbon object or Carbon will throw an exception 
    $date = Carbon::parse(request()->input('month')); 

    $articles = NewsItem::where('created_at', function($query) use($date) { 
     $query 
      ->where('created_at', '>=', $date->startOfMonth()->toDateTimeString()) 
      ->where('created_at', '<=', $date->endOfMonth()->toDateTimeString()); 
    })->get(); 

} catch(\Exception $e) { 
    // gracefully handle Exception 
    dd($e->getMessage()); 
}