2016-11-27 68 views
0

我有兩個型號Laravel ORM created_at領域

  1. 價格

我已經建立了關係

class Station extends Model 
{ 
    protected $keyType = "string"; 
    public $incrementing = false; 

    public function prices() 
    { 
     return $this->hasMany('App\Price'); 
    } 

    public function latestPrice() 
    { 
     return $this->hasOne('App\Price')->orderBy('created_at', 'desc'); 
    } 
} 


class Price extends Model 
{ 
    protected $visible = ['created_at']; 
    public function station() 
    { 
     return $this->belongsTo('App\Station'); 
    } 
} 

我取的價格,這屬於與

$stations = Station::all(); 
    $now = new Carbon(); 

    foreach ($stations as $station) { 
     $lastPrice = $station->latestPrice; 
     $t = $lastPrice->created_at; 
     $difference = $now->diffInMinutes($test); 
     if ($difference > 4) { 
      //$this->saveNewPrice($station->id); 
     } 
    } 

但我得到錯誤「嘗試獲取非對象的屬性」。我不知道爲什麼會這樣。 如果我dd $ lastPrice-> created_at 我得到正確的結果,但如果我嘗試使用它們,我會得到錯誤。

任何人都可以幫助我解決這個錯誤?

太感謝你了, Ç

回答

2

可能有機會,對於一些station沒有price所以最好來包裝部分if子句:

foreach ($stations as $station) { 
    $lastPrice = $station->latestPrice; 
    if(lastPrice) { 
     $t = $lastPrice->created_at; 
     $difference = $now->diffInMinutes($test); 
     if ($difference > 4) { 
      //$this->saveNewPrice($station->id); 
     } 
    } 
} 
+0

,做的伎倆。男人你真棒謝謝你。 – cracker182

+0

我現在也明白了這個錯誤..我只爲ONE Station創建了一個測試用例.. foreach循環中的第二個站點觸發了錯誤..謝謝! – cracker182

+0

很高興能幫到你!如果這有助於你介意將答案標記爲已接受? –