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

Phalcon\Mvc\Model setAttributes

Hi,

I am trying to add an attribute to an existing model linked to a database.

For example, I get this when I get the attributes of the model:

Array
(
    [0] => id
    [1] => name
)

I can manually edit existing attributes with the function afterFetch in the model:

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

Without needing to add a field in my database, I would add an attribute to the model.

I tried the following code:

public function afterFetch()
{
  $this->ref = "test";
}

But without success, the attribute ref isn't added.

Is it possible?

Could you help me?

Thank you.

getAttributes and/or toArray method is always working with metadata(schema in database) so it will always check how real schema is looking for model, so fields added like those won't be returned in getAttributes or toArray method.



4.3k

Thank you for your answer.

Sorry I started using Phalcon recently so the answer to my question is may be obvious but how can I do it?

Do you have an example?



145.0k
Accepted
answer

You can't, model is object respresnetation of your records in table, if in table there is no such field then why it should be returned by any method like toArray when it doesn't exists in database? You can still add any fields to object, and use it inside object itself.

Though you can always override whatever method you want in model like toArray and add value of this field to result of parent::toArray().



4.3k
edited Jun '18

No problem.

I will add a column that will always be empty in my database, it is the simplest.

Thank you for your help.

Defintely i wouldn't do it like this. You should reconsider why you even need this field when it's not related with model, maybe it shouldn't even be in model?



4.3k
edited Jun '18

I will try to explain my problem as best as possible.

In my application, I have users who are attached to roles and these roles have modules attached to them.

This in order to create an access control system.

When I get the list of my users, I need to have the roles to which it is attached and also the modules attached to these roles.

So I used the method "hasManyToMany" many times to link all of these models together.

Here is a part of the JSON response that I have:

active: true,
login: "first_name.last_name",
first_name: "First name",
last_name: "Last name",
role: [
{
  id: "1",
  name: "Role 1",
  module: [
  {
      id: "1",
      active: true,
      name: "Module 1"
  },
  {
      id: "2",
      active: true,
      name: "Module 2"
  }]
}]

The problem is that the column module in my table role does not need to exist in my database because it is an another table that realize the links between theses models.

But at the same time I need this column when I get the model role.

I am testing something, I share my code as soon as it works.