使用Yii ActiveRecord Foreach遍历一个大表-“内存不足”错误

qkf9rpyu  于 2022-11-09  发布在  其他
关注(0)|答案(2)|浏览(149)

我在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";
}
dtcbnfnu

dtcbnfnu1#

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

$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/的例子

hi3rlvi2

hi3rlvi22#

对大数据集使用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

相关问题