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

"_related" array in models - how safe is to use it?

I have built kind of "fat" model of an SMS. I have written a method addRecipient() which creates new object of related model:


class Smses extends ModelBase {

    public function addRecipient($name, $number) {

        $recipient = new Recipients();
        $recipient->setName($name);
        $recipient->setNumber($number);

        //is using _related array safe?     
        $this->_related['recipients'][] = $recipient; 

    }

    public function initialize() {
        $this->hasMany("id","Recipients","message_id");
    }

}

In my controller I use it this way:


$sms = new Smses();
$sms->addRecipient('Marie','+49779988333');
$sms->addRecipient('Tomas','+49888777666');
$sms->create();
  1. Is this solution save? Is here the risk of some inconsistency?

  2. Does anyone know better solution for this, or have the same problem? How you solved it?


98.9k

I think it's safe and it would not change any soon. And alternative and safe way would be:

<?php

class Smses extends ModelBase
{

    public function addRecipient($name, $number)
    {

        $recipient = new Recipients();
        $recipient->setName($name);
        $recipient->setNumber($number);

        $this->tempRecipients[] = $recipient;
    }

    public function initialize()
    {
        $this->hasMany("id","Recipients","message_id");
    }

    public function save($values=null, $whitelist=null)
    {
        if (count($this->tempRecipients)) {
            $this->recipients = $this->tempRecipients;
        }
        return parent::save($values, $whitelist);
    }

}


26.3k

Thanks for your answer! But then I would need to declare new attribute e.g.


class Smses extends ModelBase {

    protected $tempRecipients = array();

    //rest of model here

}

Am I right?

Are we allowed to declare class attributes in a model? I mean attributes which are not database columns?



98.9k
Accepted
answer

Yeah, I forgot to define the property right there, and yes, you can create any properties in a model as you need.



26.3k

That is good information, thanks a lot!

There is my topic about problem with isolated transactions written week ago. I don't know if it is a bug or not - after all your/my discussion did not ended will "solved" label:) https://forum.phalcon.io/discussion/2710/error-using-isolated-transactions