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.

Virtual field

Is there any way that I can define and get a virtual field on a Model?

This is how Cakephp offering : Cakephp Doc
And Laravel use setAttribute.



17.9k

I will tell you using independent column mapping, but that will not work. Unless @phalcon says opposite, I will recomend creating a function to do that logic (I also didn't found anything in the docs).



7.2k
edited Dec '14

U can use phalcon develop-tools to create model. It can create by self. LIke this in model:

user_id is true field and id is virtual field

<?php
    public function columnMap()
    {
        return array(
            'user_id'         => 'id',
            'user_name'       => 'name',
            'user_password'   => 'password',
        );
    }


6.3k
Accepted
answer

What you are looking for is the afterFetch hook:

Docs: http://docs.phalconphp.com/en/latest/reference/models.html#initializing-preparing-fetched-records

SO Answer: http://stackoverflow.com/questions/27618616/returning-virtual-columns-in-phalcon-models/27626808#27626808

Example using the same context as your link:

public $name;
public $firstName;
public $lastName;

public function getName()
{
    return $this->getFirstName() . ' ' . $this->getLastName();
}

public function afterFetch()
{
    $this->name = $this->getName;
}


656

So, How to add VIRTUAL field, if it doen't exists in table, but I need it for result?