获取带有外键的新创建模型的验证方法

时间:2015-12-31 04:12:40

标签: php activerecord yii

我试图允许用户在一个表单中创建2个模型。 Post与Story有一对一的关系。

我的代码看起来像这样:

public function actionCreate()
{
  post = new post();
  story = new story();

  if (isset($_POST['post']))
  {
    $post->attributes = $_POST['post'];
    $story->attributes = $_POST['story'];

    // force the views to show errors for both $post and $story
    $post->validate();
    // this one will always fail because the required foreign key field is not set until the post is saved.
    $story->validate();

    if ($post->save())
    {
      $story->post_id = $post->id;
      $story->save();
    } 
  }
}

我需要调用validate以便视图显示所有字段的错误,但是由于模型刚刚创建,所以post还没有id,所以我无法将其分配给故事。这意味着验证故事总是会失败。

有没有一种方法可以验证模型是否仍然是新的,而不会丢弃外键所需的规则。

1 个答案:

答案 0 :(得分:1)

你可以用一个“场景”来做,它指示何时使用它以及哪些字段...例如..

<?php
class User extends Model
{
    public $name;
    public $email;
    public $password;

    public function rules(){
        return [
            [['name','email','password'],'required'],
            ['email','email'],
            [['name', 'email', 'password'], 'required', 'on' => 'register'],
            ];
    }
    public function scenarios()
    {
        $scenarios = parent::scenarios();
        $scenarios['login'] = ['name','password'];//Scenario Values Only Accepted
        return $scenarios;
    }
}
?>

<?php
...
class UserController extends Controller
{
    ..
    // APPLY SCENARIOS
    // scenario is set as a property
    ............
    public function  actionLogin(){
        $model = new User;
        $model->scenario = 'login';
        .............
    }
    // scenario is set through configuration
    public function  actionRegister(){
        $model = new User(['scenario' => 'register']);
        ..............
    }
}
?>

在此示例中,您可以使用两个方案'login'验证两个字段'register'验证三个..

see this doc for moore samplethisi from Yii