Pergunta

Eu tenho um modelo Audio e um modelo AudioCategory.
Ao salvar o objeto de áudio, quero validar se há pelo menos uma categoria de áudio anexada a ele.

Eu criei um validador personalizado para isso.
Tentei usar $audio->getRelated() no validador, mas ele continua tentando buscar informações no banco de dados.Como a validação ocorre antes de salvar (o que é ótimo), recebo uma lista vazia, portanto meu validador sempre retorna falso.

Quando imprimo o objeto de áudio sem salvar, posso ver minha categoria de áudio no campo _relacionado do objeto de áudio (print_r($audio);):
[_relacionado:protegido] => Matriz
([Audiocategory] => Array
(
[0] => GRQ\Áudio\Objeto AudioCategory ([...])
[1] => GRQ\Áudio\Objeto AudioCategory ([...])
)
)

Se eu tentar imprimir $audio->audiocategory diretamente, recebo um aviso:
Acesso à propriedade indefinida GRQ\Audio\Audio::audiocategory
e nada é devolvido.

Se eu chamar $audio->getRelated(), recebo um objeto do tipo Phalcon\Mvc\Model esultset\Simple com um _result vazio.(O que é lógico, já que foi procurar no banco de dados...)


Portanto, minha pergunta é:
Como posso obter e validar os campos relacionados antes de salvá-los?


Aqui está meu teste de controlador (abreviado):

    $audioCategory = new AudioCategory();
    $audioCategory->categoryId = 1;
    $arAudioCategory[0] = $audioCategory; 

    $audioCategory = new AudioCategory();
    $audioCategory->categoryId = 2;
    $arAudioCategory[1] = $audioCategory;

    $audio = new Audio();
    [...other fields initialization...]
    $audio->audiocategory = $arAudioCategory;
    $audio->save();

Aqui está o modelo de áudio (abreviado):

namespace GRQ\Audio;
use GRQ\Validator\PresenceOfRelationValidator;
class Audio extends \Phalcon\Mvc\Model {
/**
 * @Primary
 * @Identity
 * @Column(type="integer", nullable=false)
 */
public $id = 0; 
/**
 * @Column(type="integer", nullable=false)
 */
public $createdAt = 0;

[...other fields all reflecting the database...]

public function initialize() {
    $this->setSource ( "audio" );

    // table relationships
    $this->hasMany ( "id", "GRQ\Audio\AudioCategory", "audioId", array(
            'alias' => 'audiocategory'
    ) );
}

public function validation() {      
    [...other validations...]

    $this->validate ( new PresenceOfRelationValidator ( array (
            "field" => "audiocategory" 
    ) ) );

    return $this->validationHasFailed () != true;
}
}

Aqui está o modelo de categoria de áudio (abreviado):

namespace GRQ\Audio;    
class AudioCategory extends \Phalcon\Mvc\Model {
/**
 * @Primary
 * @Identity
 * @Column(type="integer", nullable=false)
 */
public $id = 0; 
/**
 * @Column(type="integer", nullable=false)
 */
public $audioId = 0;    
/**
 * @Column(type="integer", nullable=false)
 */
public $categoryId = 0;

public function initialize(){
    $this->setSource("audiocategory");
    //table relationships
    $this->belongsTo("audioId", "GRQ\Audio\Audio", "id", array(
            'alias' => 'audio'
    ));
}
}

Aqui está meu validador personalizado (que não funciona e sempre retorna falso):

namespace GRQ\Validator;

use Phalcon\Mvc\Model\Validator;
use Phalcon\Mvc\Model\ValidatorInterface;

class PresenceOfRelationValidator extends Validator implements ValidatorInterface {
public function validate($model){
    $field = $this->getOption('field');
    $message = $this->getOption('message');
    if (!$message) {
        $message = 'The required relation '.$field.' was not found';
    }

    $value = $model->getRelated($field);

    if (count($value) == 0) {
        $this->appendMessage(
                $message,
                $field,
                "PresenceOfRelation"
        );
        return false;
    }
    return true;
}
}
Foi útil?

Solução

Então, encontrei uma maneira de conseguir isso.Não tenho certeza se é a melhor maneira, mas funciona:
Como os valores estão protegidos, tive que expô-los no meu objeto.
Então criei um modelo base para me estender:

Modelo básico:

namespace GRQ;
class BaseModel extends \Phalcon\Mvc\Model {

/**
 * This function should be used to get the data in the _related field directly.
 * It is very useful if you need to validate the presence of a relation BEFORE saving in the database.
 * To initialize the field with the database content, use $this->getRelated().
 */
public function getInternalRelated(){
    return $this->_related;
}   
}

Então mudei minha classe de áudio para estender do meu modelo básico:

Modelo de áudio (simplificado):

namespace GRQ\Audio;

use Phalcon\Mvc\Model\Validator\Numericality;
use GRQ\Validator\MinValueValidator;
use GRQ\Validator\PresenceOfRelationValidator;

class Audio extends \GRQ\BaseModel {
/**
 * @Primary
 * @Identity
 * @Column(type="integer", nullable=false)
 */
public $id = 0;

/**
 * @Column(type="string", length=255, nullable=false)
 */
public $title = '';

public function initialize() {
    $this->setSource ( "audio" );

    // table relationships
    $this->hasMany ( "id", "GRQ\Audio\AudioCategory", "audioId", array(
            'alias' => 'audiocategory'
    ) );
}

public function validation() {              
    $this->validate ( new PresenceOfRelationValidator ( array (
            "field" => "audiocategory" 
    ) ) );

    return $this->validationHasFailed () != true;
}
}

Meu modelo AudioCategory (simplificado) permaneceu praticamente o mesmo:

namespace GRQ\Audio;

use Phalcon\Mvc\Model\Message;

class AudioCategory extends \GRQ\BaseModel {
/**
 * @Primary
 * @Identity
 * @Column(type="integer", nullable=false)
 */
public $id = 0;

/**
 * @Column(type="integer", nullable=false)
 */
public $audioId = 0;

/**
 * @Column(type="integer", nullable=false)
 */
public $categoryId = 0;

public function initialize()
{
    $this->setSource("audiocategory");
    //table relationships
    $this->belongsTo("audioId", "GRQ\Audio\Audio", "id", array(
            'alias' => 'audio'
    ));
}
}

E meu Validador agora usa o método getInternalRelated para validar:

namespace GRQ\Validator;

use Phalcon\Mvc\Model\Validator;
use Phalcon\Mvc\Model\ValidatorInterface;

class PresenceOfRelationValidator extends Validator implements ValidatorInterface {
public function validate($model){
    $field = $this->getOption('field');
    $message = $this->getOption('message');
    if (!$message) {
        $message = 'The required relation '.$field.' was not found';
    }

    $value = $model->getInternalRelated();

    if (count($value[$field]) == 0) {
        $this->appendMessage(
                $message,
                $field,
                "PresenceOfRelation"
        );
        return false;
    }
    return true;
}
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top