【发布时间】:2016-11-27 18:44:57
【问题描述】:
我有两个模型
- 车站
- 价格
我已经建立了关系
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 我得到了正确的结果,但如果我尝试使用它们,我会得到错误。
谁能帮我解决这个错误?
非常感谢, c
【问题讨论】: