samedi 18 avril 2015

Using SQL_CALC_FOUND_ROWS within a SqlDataProvider in Yii2

I am using a SqlDataProvider in Yii2 and here is the general example:



$count = Yii::$app->db->createCommand('
SELECT COUNT(*) FROM user WHERE status=:status
', [':status' => 1])->queryScalar();

$dataProvider = new SqlDataProvider([
'sql' => 'SELECT * FROM user WHERE status=:status',
'params' => [':status' => 1],
'totalCount' => $count,
'sort' => [
'attributes' => [
'age',
'name' => [
'asc' => ['first_name' => SORT_ASC, 'last_name' => SORT_ASC],
'desc' => ['first_name' => SORT_DESC, 'last_name' => SORT_DESC],
'default' => SORT_DESC,
'label' => 'Name',
],
],
],
'pagination' => [
'pageSize' => 20,
],
]);


You can see this does a COUNT in a query before the actual query within the SqlDataProvider that gets the actual data results.


However I would prefer to use SLC_CALC_FOUND_ROWS as this number is a more reliable method to get the correct number that matches the actual amount of rows returned by the query inside the DataProvider as it's possible that matching rows could get added or deleted between the COUNT query and the SqlDataProvider queries and hence I need something more reliable.


I could lock the tables, but I don't think that's such as wise idea, so I need to use SQL_CALC_FOUND_ROWS to get the correct amount but I am unsure how I can do it with a dataProvider.


This would be the code to do what I want:



$sql = $this->db->createCommand("SELECT FOUND_ROWS()");
$count = $sql->queryScalar();

$dataProvider->totalCount = $count;


...but that doesn't work, so as I said I am unsure how to implement the code to work with a SqlDataProvider.


Aucun commentaire:

Enregistrer un commentaire