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.

"_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?


85.4k

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);
    }

}


17.9k

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?



85.4k
Accepted
answer

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



17.9k

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:) http://forum.phalconphp.com/discussion/2710/error-using-isolated-transactions