在Laravel(eloquent)中,将updated_at比created_at更旧的记录在2小时内完成

时间:2018-01-23 19:10:37

标签: php mysql laravel eloquent php-carbon

我想计算updated_at比created_at早2个小时的记录。

代码

$teLang = $kentekens->where('updated_at', '>', 'created_at'->subHours(2));

不幸的是,这不起作用,因为subHours(2)适用于碳,但希望你能得到这个想法。

视图

<h1>{{ $teLang->count() }}</h1>

控制器

public function create() {
        $kentekens = Kenteken::latest()
            ->where('created_at', '>=', Carbon::today())
            ->get();

        $teLang = $kentekens->where('updated_at', '>', 'created_at'->subHours(2));

        return view('layouts.dashboard', compact('kentekens', 'teLang'));
    }
谁知道怎么做?

3 个答案:

答案 0 :(得分:2)

$kentekens->whereRaw('`updated_at` > DATE_ADD(`created_at`, INTERVAL 2 HOUR)');

SQL:

select `id` from `tablename` where `updated_at` > DATE_ADD(`created_at`, INTERVAL 2 HOUR)

答案 1 :(得分:1)

Use the filter() method. Using your code logic:

$teLang = $kentekens->filter(function($i) {
    return $i->updated_at->gt($i->created_at->subHours(2));
});

Using this statement "where updated_at is 2 hours older than created_at":

$teLang = $kentekens->filter(function($i) {
    return $i->updated_at->lt($i->created_at->subHours(2));
});

答案 2 :(得分:0)

Maybe so?

public function create() {
    $kentekens = Kenteken::latest()
        ->where('created_at', '>=', Carbon::today())
        ->get();
    $cr = Carbon::create($kentekens->created_at);
    $teLang = $kentekens->where('updated_at', '>', $cr->addHours(2));

    return view('layouts.dashboard', compact('kentekens', 'teLang'));
}