Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

Models sql datediff

Hi!

I want to retrieve all posts older than 1h using datediff but I get the following error:

Phalcon\Mvc\Model\Exception: Column 'HOUR' doesn't belong to any of the selected models...

My code:

$h = 1;

Posts::find(['DATEDIFF(HOUR, created_at, NOW()) > :h:',
'bind' => ['h' => $h]
]);
edited Mar '16

What database you are using ? beacause DATEDIFF in sql and mysql looks diffrently



258

I'm using mysql

Also possibly you should use TIMEDIFF in your case i guess.



4.6k
edited Mar '16

I think use Carbon should be more universal, like:

   public function getResultsBefore(Carbon\Carbon $time)
    {
        $className = get_class($this);
        return $this->getModelsManager->createBuilder()
            ->from($className)
            ->where('created_at < :time:',['time'=>$time->toDateTimeString()])
            ->getQuery()->execute();
    }

Then you could use like:

$hour = 1;
$posts = (new Posts)->getResultsBefore(\Carbon\Carbon::now()->addHour(-$hour));


4.6k
edited Mar '16

Or you could use Carbon like this:

    $hour = 1;
    $time = \Carbon\Carbon::now()->addHour(-$hour)->toDateTimeString();
    $posts = Posts::find(['created_at > :time:','bind'=>['time'=>$time]]);


258

I ended up using timediff and extracted the hour difference:

$h = 1;

Posts::find(['HOUR(TIMEDIFF(created_at, NOW())) > :h:',
'bind' => ['h' => $h]
]);