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

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.



33.8k

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).



15.6k
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.9k
Accepted
answer

What you are looking for is the afterFetch hook:

Docs: https://docs.phalcon.io/en/latest/reference/models.html#initializing-preparing-fetched-records

SO Answer: https://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;
}


7.0k

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