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

problem with fat model - method adding related entities

I have two models: Messages and its child model Parameters. I want my Messages model to be "fat", I mean to be able to create its child model records.

For example, with this code:


$sms = new Messages();
$sms->addParameter("value1");
$sms->addParameter("value2");
$sms->save();

I want that above code creates 1 record of Messages and 2 related records of Parameters. Or more than 2.

Now only 1 record of Parameters is being created - allways the first one. I don't know why... :/

My code:

Messages model:


class Messages extends ModelBase {

    public $id;
    public $phone_id;

    public function addParameter($name, $value) {

        $param = new Parameters();
        $param->name = $name;
        $param->value = $value;
        $this->parameters = $param;

    }

    public function initialize() {

        $this->hasMany(
            "id",
            "Parameters",
            "message_id"
        );

    }

}

Parameters model:


class Parameters extends ModelBase {

    public $id;
    public $message_id;
    public $name;
    public $value;

    public function initialize() {

        $this->belongsTo(
            'message_id',
            'Messages',
            'id',
            array('alias' => 'Message')
        );

    }

}

Controller:


$sms = new Messages();
$sms->phone_id = 5;
$sms->addParameter('key',213233);
$sms->addParameter('locale','cz-CZ');
$sms->create(); //only 1 record is created, only the first one (key/213233)

TIA a lot for any help to solve it!



26.3k
Accepted
answer

The problem was that each time the method addParameter() was invoked, the array of related model was overwritten by $this->parameters = $param;.

I have solved it using protected _related field.

My bypass:


class Messages extends ModelBase {

    public function addParameter($name, $value) {

        $param = new Parameters();
        $param->name = $name;
        $param->value = $value;

        $this->_related['parameters'][] = $param;

    }

}

But I worry if this is safe...