0

在一个使用 Yii 的简单项目中,我有一个模型:

签到.php

 * The followings are the available columns in table 'checkins':
 * @property integer $id
 * @property integer $user_id
 * @property integer $item_id
 * @property double $lat
 * @property double $long

$user_id 和 $item_id 这两个值属于另外两个表:

public function relations()
{
    // NOTE: you may need to adjust the relation name and the related
    // class name for the relations automatically generated below.
    return array(
        'user' => array(self::BELONGS_TO, 'Users', 'user_id'),
        'item' => array(self::BELONGS_TO, 'Items', 'item_id'),
    );
}

我定义了一些验证器:

public function rules()
{
    // NOTE: you should only define rules for those attributes that
    // will receive user inputs.
    return array(
        array('user_id, item_id, lat, long', 'required'),

        array('item_id', 'exist', 'on'=>'create', 'attributeName'=>'id', 'className'=>'Items'),

        array('user_id, item_id', 'numerical', 'integerOnly'=>true),
        array('lat, long', 'numerical'),
        // The following rule is used by search().
        // Please remove those attributes that should not be searched.
        array('id, user_id, item_id, lat, long', 'safe', 'on'=>'search'),


    );
}

在 actionCreate 方法 save() 执行时,所有验证器都在工作,但不是用于检查模型项目中是否存在外部密钥的验证器

array('item_id', 'exist', 'on'=>'create', 'attributeName'=>'id', 'className'=>'Items'),

如果我尝试保存在 item_id 中具有值的 Checkins 而在 Items 中没有相同的 id,我不会出现任何验证错误。

这是正确的方法吗?

谢谢

4

1 回答 1

0

我认为这很可能是因为您'create'在保存之前没有将模型的场景设置为(我只是在猜测,因为您没有将$checkin->save()代码附加到控制器的actionCreate.)中。另一个验证最有可能起作用,因为它们没有设置为特定场景(即它们将在所有验证中工作。)。

例如,如果没有 id 为 5 的 Item,下面的代码

    $checkin = new Checkin();
    $checkin->text = 'test';
    $checkin->item_id = 5;
    if (!$checkin->validate()){
        print_r($checkin->errors);
    }

将正常工作,因为Checkin's 方案未设置为'create'(默认为'insert')。但我尝试了下面的代码

    $checkin = new Checkin();
    $checkin->scenario = 'create'; 
    //or you can set it in the instantiation 
    //$checkin = new Checkin('create');
    $checkin->text = 'test';
    $checkin->item_id = 5;
    if (!$checkin->validate()){
        print_r($checkin->errors);
    }

这将导致验证错误。

你能粘贴你的模型保存代码吗?

于 2012-04-04T01:26:53.460 回答