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 add custom attribute to the result from find()

Hi There,

I have a custom requirement where i need to add an additiional attribute to the resultset from find()/ findFirst().

Eg: i have table user with fields id, name, status

User::find("id=1");
User::findFirst("id=1");
User::findFirst();
User::findFirstByid(1);

The regular output contains all the three fields from the database table. But, the expected result would be:

{
"user": {
      "id": 1,
      "name": "test user",
      "status": 1,
      "blah": "Hello World!"
    }
}

Thanks in Advance!



3.6k

I've found it usefull to wrap the results from the model layer into another, higher layer. In this instance, it would look something like this:

$user = User::findFirstById(1);

$entity = new UserEntity();  // A custom class, created and maintained by you
$entity->populate($user);
$entity->setBlah('Hello world!');


2.5k

Thanks Rob. It looks like a nice idea of having a wrapper and at the same it would be a overhead where find() method returns a Phalcon\Mvc\Model\Resultset\Simple.

I am even looking for a simpler approach.

Thanks again for a smarter idea.

"columns" => "*, `HelloWorld` as blah"

Keep in mind it will return row object i guess.



2.5k
"columns" => "*, `HelloWorld` as blah"

Keep in mind it will return row object i guess.

Already tried that one. But, its output is strange when i used '*'

{
  "user": {
    "id": 1,
    "name": "user",
    "status": 1
  },
      "blah": "HelloWorld"
}

But, instead * if i use all column names, its okay "columns" => "id, name, status, 'Hello Word!' as blah"

{
    "id": 1,
    "name": "user",
    "status": 1,
    "blah": "Hello Word!"
}

Only concern is to remembering all the column names when they are more....