We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Mapping database date type to \datetime or any other object

I have a class which contains two other classes in its body:

class Leave
{
    /**
     * @var Day
     */
    private $fistDay;
    /**
     * @var Day
     */
    private $lastDay;
}

Day is a simple container over a php \Datetime class which implements some logic about operations on days to make code easier to read.

When I specify type of firstDay column in database as 'date', phalcon model generator maps it as 'string' while I'd like to use my custom class instead. Is there any way to do it? Making another table just for days seems to be an overkill ;-)

Cheers.

edited Feb '16

Do __construct method in your class. And create afterFetch method which will set lastDay to to object of this class. Also dont forgot about beforeSave - cuz you need to change this object back to string or create __toString method in your class.

They problem with this is if you are using modelsManager or dont get full object - it wont work.



7.0k
edited Feb '16

You can use class Carbon to easy these kind of datetime manipulating tasks, for example:

mysql:

updated_at timestamp NULL created_at timestamp NULL

php:

  use Carbon\Carbon;
  use Phalcon\Mvc\Model;
  abstract class myModel extends Model{
    public function beforeSave()
    {
        if($this->created_at != null) {
            if(is_a($this->created_at,'\Carbon\Carbon'))
                $this->created_at = $this->created_at->toDateTimeString();
        }else{
            $this->created_at = Carbon::now()->toDateTimeString();
        }

        $this->updated_at = Carbon::now()->toDateTimeString();
        return true;
    }
    public function afterFetch()
    {
        if(isset($this->created_at)) $this->created_at = Carbon::parse($this->created_at);
        if(isset($this->updated_at)) $this->updated_at = Carbon::parse($this->updated_at);
    }
  }

Hope this can help you!