2016-12-15 23 views
0

爲了列出所有的文章,包括在我們的目錄中的當前月,我已經使用Laravel寫了下面的查詢(片):Laravel:查詢dinamically時間表達式

$current_month_film = DB::table('films') 
     ->join('categories', 'films.category_id', '=', 'categories.id') 
     ->select('films.*', 'categories.*') 
     ->whereMonth('films.created_at', '=', '12') 
     ->orderBy('films.created_at', 'desc') 
     ->get(); 

它可以完美運行。它顯示本月添加了5部電影。唯一的問題是,我很難編碼十二月(月= 12)。下個月我需要更新到月= 1。這是一個不好的解決方案。

問題是:

1-我怎麼總能得到當前月份?試圖

->whereMonth('films.created_at', '=', 'NOW')

回饋不是錯誤,但列表來空。十二月有5部電影加入。

2-我顯示在前端的消息:

5 films added in Month 12 

有一種方法來改變月= 12到十二月,並顯示像一個友好的消息:

5 films added in December" 

3-更好的方法是展示過去30天內的電影。我沒有找到時間功能。

任何幫助將apreciated

回答

2

嘗試利用Carbon其自帶默認使用Laravel。

  1. ->whereMonth('films.created_at', '=', Carbon::now()->month)
  2. 你既然知道$month = 12,你可以這樣做

    $someDate = Carbon::parse("2016" . $month . "01"); //someDate is a Carbon object now 
    $output = "added in Month " . $someDate->format('F'); 
    
  3. 檢索數據1月齡:

    ->whereBetween('films.created_at', [Carbon::today()->subMonth(), Carbon::today()])` 
    

編輯:把在use Carbon;之前你的class SomeClassName {。您可能想要閱讀有關Namespace

+1

如果只需要月份編號,'date('m')'就足夠了。 – Leif

+0

這是什麼意思,「它是默認在Laravel中出現的?我得到一個錯誤,指出」class carbon not found「。我仍然需要編寫這個類和每個方法來獲得我想要的東西嗎? –

+0

'use Carbon \ Carbon;'在你文件的最上面 - 好吧,在Laravel的'use'周圍使用 –