【问题标题】:Phalcon: How to get/validate related objects before saving?Phalcon:如何在保存之前获取/验证相关对象?
【发布时间】:2014-04-11 19:25:26
【问题描述】:

我有一个模型 Audio 和一个模型 AudioCategory。
当我保存音频对象时,我想验证它是否附加了至少 1 个音频类别。

我为此创建了一个自定义验证器。
我尝试在验证器中使用 $audio->getRelated(),但它一直试图在数据库中获取信息。由于验证发生在保存之前(这很好),所以我收到一个空列表,因此我的验证器总是返回 false。

当我打印音频对象而不保存时,我可以在音频对象的 _related 字段中看到我的音频类别 (print_r($audio);):
[_related:protected] => 数组
( [音频类别] => 数组
(
[0] => GRQ\Audio\AudioCategory 对象 ([...])
[1] => GRQ\Audio\AudioCategory 对象 ([...])
)
)

如果我尝试直接打印 $audio->audiocategory,我会收到一条通知:
访问未定义的属性 GRQ\Audio\Audio::audiocategory
并没有返回任何内容。

如果我调用 $audio->getRelated(),我会得到一个 Phalcon\Mvc\Model\Resultset\Simple 类型的对象,其 _result 为空。 (这是逻辑,因为它在数据库中搜索......)


因此,我的问题是:
如何在保存之前获取并验证相关字段?


这是我的(缩短的)控制器测试:

    $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();

这是(缩短的)音频模型:

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

这是(缩短的)音频类别模型:

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

这是我的自定义验证器(不起作用并且总是返回 false):

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

【问题讨论】:

  • 你试过用audioCategory和audio_category访问吗?
  • 我刚试过没有更多结果。虽然,我现在在 audio 和 audioCategory 的初始化中都设置了一个别名。但没有更多的运气......我已经更新了上面的代码以反映这一点。
  • 基本上,在保存音频(及其关系)之前,使用 $audio->audiocategory 或 $audio->getaudiocategory() 不起作用。当我尝试在模板中打印这些内容时,我得到一个空白页...: echo '

    audio:
    '; print_r($audio->audiocategory);回声'
    '; //空白页 echo '

    audio:
    '; print_r($audio->getaudiocategory()); echo '
    ';//空白页
  • 真诚地,我也没有成功的相关记录。让我们希望有人知道发生了什么......

标签: php validation phalcon


【解决方案1】:

所以,我找到了实现这一目标的方法。不确定这是最好的方法,但它有效:
由于这些值是受保护的,我不得不从我的对象中公开它们。
所以我创建了一个基础模型来扩展自己:

基础模型:

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

然后我更改了我的音频类以扩展我的基本模型:

音频模型(简化):

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

我的 AudioCategory 模型(简化)几乎保持不变:

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

而我的验证器现在使用 getInternalRelated 方法来验证:

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

【讨论】:

    猜你喜欢
    • 2012-11-16
    • 1970-01-01
    • 1970-01-01
    • 2022-08-08
    • 1970-01-01
    • 2013-01-29
    • 2023-03-16
    • 2014-05-30
    • 2013-01-11
    相关资源
    最近更新 更多