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.

HasMany with previously declared field

I'm trying to implement some core classes for a project and I'm using models relationships. To help explain the problem lets suppose I have two models: Model and RelatedModel, where Model.Id relates to RelatedModel.Id. I declare a HasOne in the Model class passing 'Id', 'RelatedModel', 'Id'... so its expected that I use a "RelatedModel" field in the Model class to create the relation... something like:

$model = new Model(); $related = new RelatedModel(); $model->RelatedModel = $related; $model->save();

And that works just fine... But lets suppose I want to use a IDE autocomplete feature, or that I enforce oop as a rule of conduct. So I need to declare the 'RelatedModel' field in the Model class... But when I do that the $related is not send to the database, its ignored.

Is this supposed to happen? If so, how do I enforce oop when using model relationships?

Thanks in advance!



106.2k
Accepted
answer
edited Dec '16

Yes it is. Phalcon is using magic setters/getters for relations. Since it's no longer no existing property it doesn't work. Also most likely you should have belongsTo when using hasMany. You can always add getter like this:

public function getRelatedModels()
{
    return $this->getRelated('alias');
}

This work like a charm, to make sure no needed queries will be executed set reusable in relation options to true.

Thank you

Yes it is. Phalcon is using magic setters/getters for relations. Since it's no longer no existing property it doesn't work. Also most likely you should have belongsTo when using hasMany. You can always add getter like this:

```php public function getRelatedModels() { return $this->getRelated('alias'); } ```

This work like a charm, to make sure no needed queries will be executed set reusable in relation options to true.