当前位置: 动力学知识库 > 问答 > 编程问答 >

php - Eloquent Relationship stopped working and doesn't work anymore

问题描述:

I have this two models below that have a 1 on 1 relationship. They worked like a charm but suddenly ( maybe because some updates in the database ( added 2 new columns )) it stopped working. I am getting the error only when I try to reach a payment that is part of a fare. For example.

$fare->payment->amount;

Gives an error: Trying to get property of non-object

When I use a DD(); to debug I see the following show up. Pastebin

Does someone know what to do or how to solve this?

Below u can find the models

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;

}

}

网友答案:

Since it worked, I think you added a "payment" column in your table, so with $fare->payment you access to the attribute not the relation, you have 3 choices:

  1. rename your column
  2. use $fare->payment()->first()->amount
  3. rename your relation
网友答案:

The error is as given below:

Trying to get property of non-object

It rises when you access payment from Fare like this:

$fare->payment->amount;

According to your dd() result you have some Fare objects without related Payment:

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

So, in the returned collection you have some Fare objects without related Payment so this error is arising, make sure that the Fare object has a related Payment object before you try to access one. You may try something like this:

{{ $fare->payment ? $fare->payment->amount : '' }}
分享给朋友:
您可能感兴趣的文章:
随机阅读: