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

how to dynamically add attribute to a model when Filtering Resultsets

i have two models, one is Robots, another is RobotsTypes. Robots has a 1-1 relationship with RobotsTypes.

CREATE TABLE robots (
    id int(10) unsigned NOT NULL AUTO_INCREMENT,
    name varchar(70) NOT NULL,
    type_id int(3) NOT NULL,
    PRIMARY KEY (id)
);

CREATE TABLE robots_types (
    type_id int(3) unsigned NOT NULL AUTO_INCREMENT,
    type_name int(10) NOT NULL,
    PRIMARY KEY (type_id),
);

i want $robots has typeName attribute, so i did this

$robots =  Robots::find();

$robots = $robots->filter(
    function ($robot) {
        $robot->typeName = $robot->RobotsTypes->typeName ;

        return $robot;
  }
);

but it doesn't work. why? is there another simple way to do this?

I'm not sure what you gain by being able to type $robot->typeName instead of $robot->RobotsTypes->typename.

Regardless, I think the best way to do this would be to override __get(). That method can then access $this->RobotsTypes->typename and return it.

Using filter() like you have will cause a DB query for every robot, regardless of whether or not you need $typename. Overriding __get will lazy-load when necessary.

edited Dec '18

i want $robot->typeName instead of $robot->RobotsTypes->typename because i need to output JSON for AJAX.

this way is working for me, but i do not know whether it's a simple way

$obj = new \stdClass;
$robots = $robots->filter(
    function ($robot)  use ($obj){
        $obj->id = $robot->id;
        $obj->name = $robot->name;
        $obj->typename = $robot->RobotsTypes->typeName;

        return  $obj;
    }
);

echo json_encode($robots);

I checked the offical Tutorials about PHQL, then i use PHQL

 $phql = 'SELECT Robots.*, RobotsType.typename  FROM Robots JOIN RobotsType';

$rows = $manager->executeQuery($phql);

echo json_encode($rows);

this is what i want。But how to implement it via model