2014-09-27 15 views
0

我有這兩個模型下面有1對1的關係。他們像一個魅力工作,但突然(可能是因爲數據庫中的一些更新(添加2個新列)),它停止工作。只有當我嘗試達到屬於票價一部分的付款時,我纔會收到錯誤。例如。雄辯關係停止工作,不再工作

$fare->payment->amount; 

給出一個錯誤:試圖當我使用一個DD()來獲得非對象 的屬性;調試我看到下面的顯示。 Pastebin

有人知道該怎麼辦或如何解決這個問題嗎?

下面u能找到型號

class Fare extends Eloquent { 

    protected $table = 'fare'; 

    public function payment() 
    { 
     return $this->hasOne('Payment'); 
    } 

    public function email() 
    { 
     return $this->email; 
    } 

    public function getTimeagoAttribute() 
    { 
     $date = Carbon::createFromTimeStamp(strtotime($this->created_at))->diffForHumans(); 
     return $date; 
    } 

} 

class Payment extends Eloquent { 

    protected $table = 'payment'; 

    public function fare() 
    { 
     return $this->belongsTo('Fare'); 
    } 

    public function status() 
    { 
     return $this->belongsTo('Status'); 
    } 

    public function scopeApproved($query) 
    { 
     return $query->where('status', 1); 
    } 

    public function scopeDeclined($query) 
    { 
     return $query->where('status', 2); 
    } 

    public function getTimeagoAttribute() 
    { 
     $date = Carbon::createFromTimeStamp(strtotime($this->created_at))->diffForHumans(); 
     return $date; 
    } 


} 
+0

無關的你的問題,但默認你的'created_at'和'updated_at'列是Carbon對象。所以'getTimeagoAttribute()'可以簡單地返回'$ this-> created_at-> diffForHumans()'! – Dwight 2014-09-28 11:30:00

回答

1

由於它的工作,我想你加入你的表中的「付款」一欄,所以用$fare->payment您訪問屬性沒有關係,你有3種選擇:

  1. 重命名列
  2. 使用$fare->payment()->first()->amount
  3. 重命名你的關係
+0

啊,我只是想出了它的MySQL,因爲這裏的其他答案..所以它導致我正確的方向,但這是確切的問題:) – Reshad 2014-09-27 19:23:53

1

如下面給出的錯誤:

$fare->payment->amount; 

據:

Trying to get property of non-object 

它,當你從Fare訪問payment這樣上升到你的dd()結果你有一些Fare個對象,而相關Payment

// In your pastebin you have similar entries 
["payment"]=> 
NULL 

因此,返回集合中你有一些Fare對象,而相關Payment所以這個錯誤出現,請確保Fare對象有一個相關的Payment對象您嘗試訪問一個前。您可以嘗試這樣的事:

{{ $fare->payment ? $fare->payment->amount : '' }} 
+0

感謝您的回覆:)感謝您的回答,我明白了。你的回答並不完全正確,但它幫助我走向正確的方向。我在票價表中添加了一個名爲payment的列..我真的很傻:) – Reshad 2014-09-27 19:23:07

+0

既然你有'一對一'的關係,並且你已經使用了'$ this-> hasOne('Payment')'那麼你只會得到一個「Payment」對象不是一個集合。 – 2014-09-27 19:26:20