【问题标题】:Laravel ORM created_at FieldLaravel ORM created_at 字段
【发布时间】:2016-11-27 18:44:57
【问题描述】:

我有两个模型

  1. 车站
  2. 价格

我已经建立了关系

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

【问题讨论】:

    标签: php laravel orm eloquent


    【解决方案1】:

    对于某些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);
            }
        }
    }
    

    【讨论】:

    • 我现在也明白错误了..我只为ONE Station创建了一个测试用例..foreach循环中的第二个站触发了错误..谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-28
    • 2020-03-28
    • 2015-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多