Reputation: 1358
I need to get some records from a table called Hospitals with the same criteria:
First get the ones which city match with $city param. Second get the ones which state match with $state param. Third get the rest ordered by A-Z
I need to get all of them in one query since I'm going to paginate the resulset, so i choose CSqlDataProvider, which receives a sql, the count and the pagination as initial configuration: http://www.yiiframework.com/doc/api/1.1/CSqlDataProvider
so, I was thinking of making extra fields as booleans and sort them by theese, like: same_city, same_state.
so let's assume this is the resulted sql (when i replaced with params values from request) that goes to the CSqlDatProvider:
select *,
IF(city like '%San Antonio%', 1, 0) as same_city,
IF(state=44, 1, 0) as same_state
from hospitals
order by same_city DESC, same_state DESC, hospital_name ASC;
If i assign this string to the CSqlDataProvider i won't be able to paginate since I'm hardcoding the order... however I need this specific order so the criteria of records retrieving is successful.
$arHospitals = new CSqlDataProvider($sql, array(
'totalItemCount'=>$count,
'pagination'=>array(
'pageSize'=>30,
),
));
if I run the code above, it will return the whole matching records, no matter of pageSize. However if I use the pagination according to yii documentation, I will get only the records that pagination indicates, but with a non-sense order for me... I need the following order in the fields: same_city DESC, same_state DESC, hospital_name ASC.
$arHospitals = new CSqlDataProvider($sql, array(
'totalItemCount'=>$count,
'sort'=>array(
'attributes'=>array(
'asc'=>array('hospital_name'),
'desc'=>array('same_city', 'same_state'),
),
),
'pagination'=>array(
'pageSize'=>30,
),
));
Any ideas of how to solve this? If I'm missing some key information about the problem please let me know.
Upvotes: 3
Views: 1900
Reputation: 532
Something like this should work:
$arHospitals = new CSqlDataProvider($sql, array(
'totalItemCount'=>$count,
'sort'=>array(
'attributes'=>array(
'virtualFieldName'=>array( //virtual field name
//give no possibility to sort in any other order than
'asc'=>'same_city DESC, same_state DESC, hospital_name ASC',
'desc'=>'same_city DESC, same_state DESC, hospital_name ASC',
'label'=>'Default Sort Order'
),
),
'defaultOrder'=>array(
'virtualFieldName'=>CSort::SORT_ASC, //default sort value
),
),
'pagination'=>array(
'pageSize'=>30,
),
));
See http://www.yiiframework.com/doc/api/1.1/CSort#attributes-detail for more info.
Upvotes: 2