2017-01-05 188 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()); 
}