【问题标题】:Yii record is not inserting into DBYii 记录未插入数据库
【发布时间】:2014-02-04 11:30:50
【问题描述】:

下面是我的控制器和模型逻辑 - 我刚刚开始安装一个准系统 Yii 以进一步使用它。

我没有收到任何错误,但在数据库中看不到新条目 - 我的数据库已在 main.php 中配置(这在 Gii 运行时有效)。

// controllers/PageController.php
class PageController extends Controller
{
    public function actionSave($value='')
    {
        $pageObj = new Page;
        $pageObj->savePage();
    }     
}


// models/Page.php

class Page extends CActiveRecord
{
/**
 * @return string the associated database table name
 */
public function tableName()
{
    return 'page';
}

/**
 * @return array validation rules for model attributes.
 */
public function rules()
{
    // NOTE: you should only define rules for those attributes that
    // will receive user inputs.
    return array(
        array('title, date_updated', 'required'),
        array('live', 'numerical', 'integerOnly'=>true),
        array('user_id', 'length', 'max'=>10),
        array('title', 'length', 'max'=>100),
        array('content, date_published', 'safe'),
        // The following rule is used by search().
        // @todo Please remove those attributes that should not be searched.
        array('id, user_id, live, title, content, date_updated, date_published', 'safe', 'on'=>'search'),
    );
}

/**
 * @return array relational rules.
 */
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(
        'comments' => array(self::HAS_MANY, 'Comment', 'page_id'),
        'user' => array(self::BELONGS_TO, 'User', 'user_id'),
        'files' => array(self::MANY_MANY, 'File', 'page_has_file(page_id, file_id)'),
    );
}

/**
 * @return array customized attribute labels (name=>label)
 */
public function attributeLabels()
{
    return array(
        'id' => 'ID',
        'user_id' => 'User',
        'live' => 'Live',
        'title' => 'Title',
        'content' => 'Content',
        'date_updated' => 'Date Updated',
        'date_published' => 'Date Published',
    );
}

/**
 * Retrieves a list of models based on the current search/filter conditions.
 *
 * Typical usecase:
 * - Initialize the model fields with values from filter form.
 * - Execute this method to get CActiveDataProvider instance which will filter
 * models according to data in model fields.
 * - Pass data provider to CGridView, CListView or any similar widget.
 *
 * @return CActiveDataProvider the data provider that can return the models
 * based on the search/filter conditions.
 */
public function search()
{
    // @todo Please modify the following code to remove attributes that should not be searched.

    $criteria=new CDbCriteria;

    $criteria->compare('id',$this->id,true);
    $criteria->compare('user_id',$this->user_id,true);
    $criteria->compare('live',$this->live);
    $criteria->compare('title',$this->title,true);
    $criteria->compare('content',$this->content,true);
    $criteria->compare('date_updated',$this->date_updated,true);
    $criteria->compare('date_published',$this->date_published,true);

    return new CActiveDataProvider($this, array(
        'criteria'=>$criteria,
    ));
}

/**
 * Returns the static model of the specified AR class.
 * Please note that you should have this exact method in all your CActiveRecord descendants!
 * @param string $className active record class name.
 * @return Page the static model class
 */
public static function model($className=__CLASS__)
{
    return parent::model($className);
}

public function savePage($value='')
{
    $page = new page;
    $model->isNewRecord = true;
    $model->primaryKey = NULL;
    $page->title='sample page';
    $page->content='content for the sample page';
    $page->save(false);
}
}

【问题讨论】:

  • 你能用你模型的 rules() 方法编辑你的帖子吗?
  • 为什么有人对此投了反对票,甚至没有解释原因??

标签: database activerecord yii frameworks


【解决方案1】:

在 Yii 中,当你想插入一个有一些空列的表时,你必须在你的规则中添加空列 SAFE 如下所示:

array('primaryKey','safe'),

现在,Yii 知道primaryKey 是一个空列。所以,插入到当前模型中是没有问题的。

请注意,当您使用 FALSE 调用 save() 方法时,您是在告诉您的模型不要在插入时进行验证。

另外,跳过可能的错误的正确方法是在插入之前验证您的模型,如下所示:

if($model->validate()){
    // VALIDATE, YOU CAN CALL SAVE FUNCTION
}else{
    //here you can send an error message via FLASH or you can debug what the exact error is like below:
    CVarDumper::dump($model->getErrors(),5678,true);
    Yii::app()->end();
}

希望对你有帮助

【讨论】:

  • 给了你答案,因为你已经超越了谢谢队友真的很感激
  • CVarDumper() 也很棒!我不再需要 var_dump() 或 print_r() :)
  • 不客气,亲爱的。 Yii 真的很强大,有很多工具可以比以前更轻松地完成工作。
【解决方案2】:

如此简单...我有时讨厌 Yii :-)

必须将 save() 设置为 save(false)

    $page = new page;
    $page->isNewRecord = true;
    $page->primaryKey = NULL;
    $page->title='sample page';
    $page->content='content for the sample page';
    $page->save(false);

【讨论】:

  • 如果为 false,您是在告诉 Yii 跳过验证
  • 如果你用模型的 rules() 方法修改你的问题,我会正确地描述你
  • 好的..我已经添加了整个模型:)
【解决方案3】:

谢谢 - 我错过了一些专栏..(我很傻) 在上面的帮助下进一步改进功能..

public function savePage()
{
    $page = new page;
    $page->isNewRecord = true;
    $page->primaryKey = NULL;
    $page->user_id = 1;
    $page->live = 0;
    $page->content='content for the sample page';
    $page->date_updated = date('Y-m-d H:i:s');
    $page->date_published = date('Y-m-d H:i:s');        
    $page->title='sample page';

    if ($page->validate()) {
        $page->save();
    } else {
        CVarDumper::dump($page->getErrors(),5678,true);
        Yii::app()->end();          
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-19
    • 2013-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多