relationship one to many

I want to save the entity Conteudo with many ArquivoDigital.

Conteudo.php

public $arquivosDigitais;

public function setArquivosDigitais($arquivosDigitais) {
    $this->arquivosDigitais = $arquivosDigitais;
    return $this;
}

public function getArquivosDigitais() {
    return $this->arquivosDigitais;
}

public function initialize()
{
    $this->hasMany('id', 'ArquivoDigital', 'conteudo', array(
        'alias' => 'ArquivoDigital', 
        'foreignKey' => array(
            "action" => \Phalcon\Mvc\Model\Relation::ACTION_CASCADE)
        )
    );
    $this->hasMany('id', 'Revisaoconteudo', 'conteudo', array('alias' => 'Revisaoconteudo'));
    $this->belongsTo('disciplina', 'Disciplina', 'id', array('alias' => 'Disciplina'));
}

ArquivoDigital.php

public function initialize()
{
    $this->belongsTo('conteudo', 'Conteudo', 'id', array(
        'alias' => 'Conteudo', 
        'foreignKey' => TRUE
        )
    );
}

ConteudoController.php

$conteudo = new Conteudo();
$conteudo->setTexto($this->request->getPost("texto"));
$conteudo->setData($this->request->getPost("data"));
$conteudo->setTags($this->request->getPost("tags"));
$conteudo->setDisciplina($this->request->getPost("disciplina"));

$arquivosDigitais = array();
$arquivosDigitais[] = new ArquivoDigital();
$arquivosDigitais[0]->setTipo('pdf');

$arquivosDigitais[] = new ArquivoDigital();
$arquivosDigitais[1]->setTipo('jpeg');

$conteudo->setArquivosDigitais($arquivosDigitais);

$conteudo->save();

table conteudo

CREATE TABLE conteudo ( id bigint(19) UNSIGNED NOT NULL, texto text, data date NOT NULL, tags varchar(255) DEFAULT NULL, disciplina bigint(19) UNSIGNED NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8;

table arquivodigital

CREATE TABLE arquivodigital ( id bigint(19) UNSIGNED NOT NULL, tipo varchar(50) NOT NULL, conteudo bigint(19) UNSIGNED NOT NULL -- Foreign Key conteudo.id ) ENGINE=InnoDB DEFAULT CHARSET=utf8;

In table conteudo a record has saved, but the records hasn't saved in table arquivodigital.

What's wrong?

Thanks.



1.7k
edited Jan '17

Maybe because column id in table arquivodigital is not autoincrament and you are not setting it in controller. Try to change it to autoincrament or set it in controller to see what happening. And also use models with namespace in relation definitions

edited Jan '17
public function setArquivosDigitais($arquivosDigitais) {
    $this->__set('ArquivoDigital', $arquivosDigitais);
    return $this;
}

public function getArquivosDigitais() {
    return $this->getRelated('ArquivoDigital');
}

Where ArquivoDigital is your alias.

Basically you have to remove property. Phalcon related records are saved using magic method, and got using getRelated.