【问题标题】:Laravel eloquent model where datetime less than or equalLaravel 雄辩的模型,其中日期时间小于或等于
【发布时间】:2019-05-10 22:36:09
【问题描述】:

我在测试模型中有一个 expire_datetime 字段,它与候选模型有很多关系。我想获得所有 exipre_datetime 小于或等于现在日期时间的测试。我正在这样做,但我得到了所有记录,日期比较不起作用。

测试模型:

    public function testcandidates()
    {
        return $this->hasMany(Candidate::class,'test_id','id');
    }

测试控制器:

$tests = Test::with([
            'testcandidates' => function ($query) {
                $query->where('result', '=', 'assigned');
             }
         ])
         ->where('expire_datetime', '<=', Carbon::now('UTC'))
         ->get();

【问题讨论】:

  • 您是否在模型中将 expire_datetime 作为日期添加到 protected $dates
  • 不,我没有。我会试试这个。
  • 这是有效的。实际上,DateTime 错误地存储在 DB 中并且没有得到正确的记录。 Datetime 是 DB 中的字符串类型,我将其更改为时间戳,并且工作正常。

标签: laravel-5


【解决方案1】:

尝试从碳中获取字符串:Carbon::now('UTC')-&gt;toDateTimeString()

$tests = Test::with(
   ['testcandidates' => function ($query) {
       $query->where('result', '=', 'assigned');
    }])
    ->where('expire_datetime', '<=', Carbon::now('UTC')->toDateTimeString())
    ->get();

【讨论】:

    猜你喜欢
    • 2017-10-31
    • 2016-07-26
    • 2018-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-31
    • 2021-08-11
    • 2023-01-18
    相关资源
    最近更新 更多