Yii的:保存在一个查询多条记录 [英] Yii: save multiple records in one query

查看:316
本文介绍了Yii的:保存在一个查询多条记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想节省了大量的CActiveRecord模型对象的一个​​循环。 我有这样的事情:

I'm trying to save a lot of CActiveRecord model objects in a loop. I have something like this:

foreach ($array_of_items as $item) {

    $values = array(
        "title"   => $item->title,
        "content" => $item->content,
    );

    $object = new MyModel;
    $object->attributes = $values;
    $object->save();

}

在我而言,这造成约400的CActiveRecord对象。在保存过程实在是太慢了,因为每个保存()查询数据库。

In my case, this creates about 400 CActiveRecord objects. The saving process is really slow, because each save() queries the database.

有没有办法来保存所有这些对象一气呵成? 是这样的:

Is there a way to save all those objects in one go? Something like:

$objects = array();

foreach ($array_of_items as $item) {

    $values = array(
        "title"   => $item->title,
        "content" => $item->content,
    );

    $object = new MyModel;
    $object->attributes = $values;
    $objects[] = $object;
}

save_all_objects($objects);

我找不到关于这个问题的任何东西。有人吗?

I could not find anything on the subject. Anyone?

推荐答案

您可以的validate()你的模型,如果它是确定可以追加这么一个sql文本插入,

you can validate() your model, and if it was ok you can append it so a sql text for insert,

和你的循环后,只需要使用数据库 CommandBuilder的()并执行prepared文本

and after your loop, just use databases commandBuilder() and execute your prepared text

$sql = '';
if($object->validate())
{
    $sql .= ',("' . $object->attr1 . '")'// append to script,(you get the idea, you need to also make a correct values)
}

...

if(!empty($sql))
{
    $sql = 'INSERT INTO table (attr1) Values' . $sql;// make complete script
    // execute that command
}

这篇关于Yii的:保存在一个查询多条记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆