2016-07-27 41 views
2

Laravel日期改變我正在寫一個範圍查詢,我傳遞一個fetch_date從基礎上created_at時間戳DB表拉東西。當我更新變量

我試圖尋找了一個月的所有記錄,但變量$fetch_date不斷變化,每當我嘗試以下方法:

//$fetch_date is a carbon instance and is equal to the month the user selected 
    //ie: Carbon {#221 ▼ 
    // +"date": "2016-07-01 00:00:00.000000" 

    //Create the next_month 
    $next_month = $fetch_date->addMonth(); 
    //Format next_month as a string 
    $next_month = $next_month->format('Y-m-d'); 
    //Format fetch_date as a string 
    $fetch_date = $fetch_date->format('Y-m-d'); 

    dd($fetch_date); 
    //This now gives me 2016-08-01 - why? 

爲什麼會出現fetch_date變化?我基本上試圖保持$fetch_date當前月份和$next_month僅僅是下個月的開始。

我猜有一個真正的原因很簡單,這個我只是遠眺。

+0

我想一個月要添加到fetch_date變量。嘗試複製它,然後添加月份。 –

回答

1

因爲調用addMonth方法有副作用。

如果你看一下碳的source,你會看到所有addMonth正在做的是調用addMonths爲1的值,而這又是簡單地調用DateTime::modify。它沒有明確的文檔中闡明,但是從實施例它是非常普通的,在調用該方法修改所存儲的時間值:

實施例#1的DateTime ::修改()的例子

<?php 
$date = new DateTime('2006-12-12'); 
$date->modify('+1 day'); 
echo $date->format('Y-m-d'); 
?> 

爲了避免這種情況,保留的副本的時候周圍和修改:

$also_fetch_date = clone $fetch_date; 
$next_month = $also_fetch_date->addMonth(); 
// ... 
+0

有趣的 - 並解釋到底是什麼繼續。感謝您的詳細解釋;現在我明白了,你的糾正解決了這個問題。 – Hanny

+1

嗯,爲什麼要添加月/克隆對象,當你可以簡單地使用php的strtotime來達到預期的效果。另外,也可以在Carbon中使用' - > copy'方法在一行中完成。 –

0

好像每個月要添加到fetch_date變量。

試試這個:

$next_month = Carbon::createFromFormat('Y-m-d', $fetch_date->format('Y-m-d')); 
$next_month->addMonth(); 

dd($next_month->format('Y-m-d')); 

在碳的文檔看看:http://carbon.nesbot.com/docs/ 也許會幫助你

+0

好吧,我試過了。對於某些*瘋狂*的原因,即使將其更改爲您在此處完成的操作後,$ fetch_date仍會發生變化。 我想知道如果也許我的瀏覽器沒有緩存奇怪的東西 - 因爲我不知道它是如何可能的... – Hanny

+0

嘗試新的解決方案,創建一個新的碳對象名爲next_month –