【问题标题】:Yii - multiple records in one form submissionYii - 一个表单提交中的多个记录
【发布时间】:2012-10-17 16:53:24
【问题描述】:

有谁知道如何在 Yii 中使用一个表单添加多条记录?所有记录属于同一模型,格式相同。

非常感谢,

尼克

【问题讨论】:

  • 谢谢!正是我想要的。
  • 是否有人能够确认等效 batchCreate 方法的语法?上面链接的页面中缺少此内容。
  • 是给定的模型数量还是用户可以在填写表格时即时添加?
  • 一个固定的数字,四五个说。

标签: forms activerecord model yii


【解决方案1】:

"batchUpdate" from the guide 的等效“batchCreate”方法可能是这样的:

public function actionBatchCreate() {
    $models=array();
    // since you know how many models
    $i=0;
    while($i<5) {
        $models[]=Modelname::model();
        // you can also allocate memory for the model with `new Modelname` instead
        // of assigning the static model
    }
    if (isset($_POST['Modelname'])) {
        $valid=true;
        foreach ($_POST['Modelname'] as $j=>$model) {
            if (isset($_POST['Modelname'][$j])) {
                $models[$j]=new Modelname; // if you had static model only
                $models[$j]->attributes=$model;
                $valid=$models[$j]->validate() && $valid;
            }
        }
        if ($valid) {
            $i=0;
            while (isset($models[$i])) {
                $models[$i++]->save(false);// models have already been validated
            }
            // anything else that you want to do, for example a redirect to admin page
            $this->redirect(array('modelname/admin'));
        }
    }

    $this->render('batch-create-form',array('models'=>$models));
}

这里唯一需要担心的是必须为您保存的每个模型创建一个新实例,使用new。其余的逻辑可以按照您希望的任何方式实现,例如在上面的示例中,所有模型都在验证,然后保存,而如果任何模型无效,您可以停止验证,或者直接保存模型,在save 通话期间进行验证。所以逻辑真的取决于你应用的用户体验。

【讨论】:

  • 感谢您的回复,抱歉回复晚了。这确实有帮助。
【解决方案2】:

将此代码放在GeneralRepository.php文件名下的components文件夹中。

<?php
class GeneralRepository
{
    /**
     * Creates and executes an INSERT SQL statement for several rows.
     * 
     * Usage:
     * $rows = array(
     *      array('id' => 1, 'name' => 'John'),
     *      array('id' => 2, 'name' => 'Mark')
     * );
     * GeneralRepository::insertSeveral(User::model()->tableName(), $rows);
     * 
     * @param string $table the table that new rows will be inserted into.
     * @param array $array_columns the array of column datas array(array(name=>value,...),...) to be inserted into the table.
     * @return integer number of rows affected by the execution.
     */
    public static function insertSeveral($table, $array_columns)
    {
        $connection = Yii::app()->db;
        $sql = '';
        $params = array();
        $i = 0;
        foreach ($array_columns as $columns) {
            $names = array();
            $placeholders = array();
            foreach ($columns as $name => $value) {
                if (!$i) {
                    $names[] = $connection->quoteColumnName($name);
                }
                if ($value instanceof CDbExpression) {
                    $placeholders[] = $value->expression;
                    foreach ($value->params as $n => $v)
                        $params[$n] = $v;
                } else {
                    $placeholders[] = ':' . $name . $i;
                    $params[':' . $name . $i] = $value;
                }
            }
            if (!$i) {
                $sql = 'INSERT INTO ' . $connection->quoteTableName($table)
                . ' (' . implode(', ', $names) . ') VALUES ('
                . implode(', ', $placeholders) . ')';
            } else {
                $sql .= ',(' . implode(', ', $placeholders) . ')';
            }
            $i++;
        }
        $command = Yii::app()->db->createCommand($sql);
        return $command->execute($params);
    }
}

以及在任何地方使用:

$rows = array(
    array('id' => 1, 'name' => 'John'),
    array('id' => 2, 'name' => 'Mark')
);
GeneralRepository::insertSeveral(User::model()->tableName(), $rows);

这只是执行一个查询。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-03
    • 1970-01-01
    • 2012-01-23
    相关资源
    最近更新 更多