控制器无法插入yii中的通知表


Controller cannot insert into notification table in yii

所以我有一个主表comment,它有许多字段。然后我想插入一些字段到notifications表每当一个新的记录被插入到comment

在控制器中,最初我有这个,它用于comment表:

public function actionCreate() {
    $model = new Comment;
    if (isset($_POST['Comment'])) {
        $model->attributes = $_POST['Comment'];
        if ($model->save())
            $this->redirect(array('view', 'id' => $model->comment_id));
    }
    $this->render('create', array(
        'model' => $model,
    ));
}

然后我为notification表添加了更多的行。但是没有成功。

public function actionCreate() {
    $model = new Comment;
    $notif = new Notifications;
    if (isset($_POST['Comment'])) {
        $model->attributes = $_POST['Comment'];
        $notif->peg = 'nofriani';
        $notif->tanggal = new CDbExpression("NOW()");
        $notif->notif = ' mengirimkan berita ';
        $notif->isi = $_POST['Comment']['post_id'];
        $notif->link = 'links';
        $notif->save();
        if ($model->save())
            $this->redirect(array('view', 'id' => $model->comment_id));
    }
    $this->render('create', array(
        'model' => $model,
    ));
}

comment表的函数仍然有效。但notifications表的一个没有。我试着重新安排位置,但什么也没发生。我也把$notif->save();改成了$notif->insert();,但还是什么都没发生。我错过了什么?

表结构:

CREATE TABLE IF NOT EXISTS notifications (
   id_notif int(11) NOT NULL AUTO_INCREMENT,
   tanggal date NOT NULL,
   peg varchar(30) NOT NULL,
   notif text NOT NULL,
   isi varchar(30) NOT NULL,
   link varchar(255) NOT NULL,
   PRIMARY KEY (id_notif)
 ) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;

我在你的代码中找不到任何错误。

下面是我调试上述任务的假设

  1. 可能是$_POST['Comment']['post_id']没有提供该值。
  2. 打印Post值并检查是否得到所有必需的值

     print_r($_POST['Comment']);
    
  3. save()之前验证$notif模型。它将显示验证错误,如果你的模型有。

    echo CActiveForm::validate($notif);
    

你可以用下面更好的方式编写上面的代码。

    $model = new Comment;
    $notif = new Notifications;
    if (isset($_POST['Comment']))
    {
        $model->attributes = $_POST['Comment'];
        if ($model->validate() && $model->save())
        {
            $notif->peg = 'nofriani';
            $notif->tanggal = new CDbExpression("NOW()");
            $notif->notif = ' mengirimkan berita ';
            $notif->isi = $_POST['Comment']['post_id']; 
            $notif->link = 'links';                
            if($notif->validate() && $notif->save())
            {
                $this->redirect(array('view', 'id' => $model->comment_id));                    
            }       
            else
            {
                echo CActiveForm::validate($notif); 
                Yii::app()->end();
            }
        }
        else
        {
            echo CActiveForm::validate($model); 
            Yii::app()->end();
        }
    }