[NFR] Adding related records: $album->songs[] = $song;
I would like to propose a new way of storing related records. All my codes continue example form the docs the http://docs.phalconphp.com/en/latest/reference/models.html#storing-related-records
Syntax
// Assign 2 songs to album, impossible now
$album->songs[] = $song1;
$album->songs[] = $song2;
Why?
It would be easier to add related records. I mean the situation when you need to add more than 1 record.
How it's done now?
Here are two ways of adding related records that I know.
Array in controller
As described in the docs. Assigning an arrays of related records.
$songs = array();
$songs[0] = $song1;
$songs[1] = $song2;
$album->songs = $songs;
Dedicated method inside model
One option is to code dedicated method in "parent" model:
//part of Album model
public function addSong($song) {
$this->_related['Songs'][] = $song;
}
Want to back this issue? Post a bounty on it! We accept bounties via Bountysource.
PHP does not trigger the magic getter when appending items to a not defined property:
<?php
class X
{
public function __set($k, $v)
{
// This is not called when appending an item
}
}
$x = new X;
$x->data[] = 1;
$x->data[] = 2;
var_dump($x);
@phalcon
class ModelField implements ArrayAccess
{
protected $values = array();
public function offsetExists($offset)
{
return isset($this->values[$offset]);
}
public function offsetGet($offset)
{
return $this->values[$offset];
}
public function offsetSet($offset, $value)
{
if (empty($offset)) {
return $this->values[] = $value;
}
return $this->values[$offset] = $value;
}
public function offsetUnset($offset)
{
unset($this->values[$offset]);
}
public function toArray()
{
return $this->values;
}
}
class Model
{
protected $fields = array();
public function __get($key)
{
if (isset($this->fields[$key])) {
return $this->fields[$key];
}
return $this->fields[$key] = new ModelField();
}
}
$model = new Model;
$model->myField[] = 1;
$model->myField[] = 2;
var_dump($model->myField->toArray());
Thank you for contributing to this issue. As it has been 90 days since the last activity, we are automatically closing the issue. This is often because the request was already solved in some way and it just wasn't updated or it's no longer applicable. If that's not the case, please feel free to either reopen this issue or open a new one. We will be more than happy to look at it again! You can read more here: https://blog.phalconphp.com/post/github-closing-old-issues