LoginSignup
2
1

More than 5 years have passed since last update.

CakePHP、MySQL登録日から○時間以上、◯時間以内のユーザーを取得

Posted at

ORM・SQLでフィルタ

登録から12時間以上、24時間未満のユーザーを取得

namespace App\Model\Table;

use App\Model\Entity\User;

$users = $this->find('all', [
            'conditions' => [
                 'TIMESTAMPDIFF(SECOND, created_at,NOW()) <' => 24 * 60 * 60,
                 'TIMESTAMPDIFF(SECOND, created_at,NOW()) >=' => 12 * 60 * 60
            ]
        ])->toArray();

PHPのDateTimeを使ってフィルタ場合

変数名がわかりづらくてすみません。。

namespace App\Model\Table;

use App\Model\Entity\User;

$now = new \DateTime();

// 現在時刻から$endTime($startTime)前の時刻を算出
$endDateTime = clone $now;
$endDateTime = $endDateTime->sub(new \DateInterval('PT86400S')); // 今から24h前
$startDateTime = clone $now;
$startDateTime = $startDateTime->sub(new \DateInterval('PT43200S')); // 今から12h前

$users = $this->find('all', [
            'conditions' => [
                 'created_at <' => $startDateTime,
                 'created_at >=' => $endDateTime
            ]
        ])->toArray();
2
1
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1