我有两个型号
我已经建立了关系
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 我得到了正确的结果,但如果我尝试使用它们,我会得到错误。
有人可以帮我解决这个错误吗?
非常感谢, ç
答案 0 :(得分: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);
}
}
}