2015-11-17 35 views
8

Ciao ragazzi sto usando codice seguente e l'opera limit doesnt, ma se vedo il comando di quello che mostra limit in questo, ma quando passo la query per ActiveDataProvider è recuperare tutti i recordLIMIT non funziona in ActiveDataProvider

$data= User::find()->where(['category_id'=> 5])->orderBy(['rand()' => SORT_DESC])->limit(4); 

    $command = $data->createCommand(); 

    $data2 = $command->queryAll();// This works fine and fetch only 4 data 

    $dataProvider = new ActiveDataProvider([ 
     'query' => $data, 

    ]); // But this displays all data without limit 

Cosa c'è che non sto facendo qui ???

risposta

19

Ecco cosa succede quando si prepara modelli in yii\data\ActiveDataProvider:

/** 
* @inheritdoc 
*/ 
protected function prepareModels() 
{ 
    if (!$this->query instanceof QueryInterface) { 
     throw new InvalidConfigException('The "query" property must be an instance of a class that implements the QueryInterface e.g. yii\db\Query or its subclasses.'); 
    } 
    $query = clone $this->query; 
    if (($pagination = $this->getPagination()) !== false) { 
     $pagination->totalCount = $this->getTotalCount(); 
     $query->limit($pagination->getLimit())->offset($pagination->getOffset()); 
    } 
    if (($sort = $this->getSort()) !== false) { 
     $query->addOrderBy($sort->getOrders()); 
    } 

    return $query->all($this->db); 
} 

Siamo interessati a questa parte:

if (($pagination = $this->getPagination()) !== false) { 
    $pagination->totalCount = $this->getTotalCount(); 
    $query->limit($pagination->getLimit())->offset($pagination->getOffset()); 
} 

Quindi, come si può vedere se l'impaginazione non è false, limite viene gestito automaticamente.

Si può solo impostare impaginazione per false e poi l'impostazione manuale del limite funzionerà:

$dataProvider = new ActiveDataProvider([ 
    'query' => $query, 
    'pagination' => false, 
]);