通过使用Yii ActiveRecord的大表来预告 - “内存不足”错误

时间:2013-11-14 09:13:28

标签: php sql yii out-of-memory cactivedataprovider

我在Yii Framework上有一个网站,我想在表格中搜索匹配的单词。

我不断获得"out of memory"(这是一张大桌子)。

我尝试使用此代码,但不断加载页面

$dataProvider = new CActiveDataProvider('Data');
$iterator = new CDataProviderIterator($dataProvider);
foreach($iterator as $data) {
    echo $data->name."\n";
}

所以我尝试了这段代码,但它一直将结果限制为10:

$dataProvider = new CActiveDataProvider('Data');
$iterator = new CDataProviderIterator($dataProvider);
foreach($dataProvider as $data) {
    echo $data->name."\n";
}

如果我这样做,我会收到“内存不足”的消息:

$dataProvider = new CActiveDataProvider('Data' array(
    'criteria'=>array(
        'order'=>'id DESC',
    ),
    'pagination' => false
));

foreach($dataProvider as $data) {
    echo $data->name."\n";
}

2 个答案:

答案 0 :(得分:0)

我不知道您为什么需要在一个页面中加载所有搜索结果,但您可以通过此代码将每页的项目数更改为所需的值(并使用分页):

$dataProvider = new CActiveDataProvider('Data' array(
    'criteria'=>array(
        'order'=>'id DESC',
        'condition' => 'town LIKE :search_town AND FK_country > :country_id',
        'params' => array(':search_town' => $search_town.'%', ':country_id' => 10)
    ),
     'pagination' => array(
         "pageSize" => 100,
         //"currentPage" => 0, //using for pagination
     )
));
$iterator = new CDataProviderIterator($dataProvider);
foreach($iterator as $data) {
     echo $data->name."\n";
}

此处http://sonsonz.wordpress.com/2011/10/14/yii-examples-of-using-cdbcriteria/更多示例

答案 1 :(得分:0)

对大数据集使用CActiveDataProvider是不明智的。特别是如果您只想对它们执行后台任务。 建议使用直接SQL并从那里开始。

根据对CreatoR答案的评论,您试图在大表中找到一些事件。举个例子:

$connection=Yii::app()->db;
$sql = "SELECT id FROM data WHERE field1 LIKE '%someValue%' OR field2 LIKE '%someValue%' OR field3 LIKE '%someValue%'";
$command=$connection->createCommand($sql);
$numberOfRestuls=$command->execute();
//if you also want to display the results :
$ids=$command->queryAll();
$criteria=new CDbCriteria;
$criteria->addInCondition('id',$ids,'OR');
$dataProvider = new CActiveDataProvider('Data', $criteria);
//etc