CSqlDataProvider or CActiveDataProvider


Do you use Activerecord or Query SQL in your big project, that have many relations ?

Yii have some data Provider:




i seem that CSqlDataProvider is very easy to implement in my project for many relation.

waiting your feedback.

It depends on what you want to achieve… if you want to just fetch data and display it somehows - use CSqlDataProvider as it will be faster and possibly less resources consuming (memory, cpu time, etc).

On the other hand - when you want to use ActiveRecord capabilities on every fetched object - use CActiveDataProvider.

I think the best is to try to achieve whatever you want using CActiveDataProvider.

If you find things getting too complicated an you are good at SQL, use CSqlDataProvider

thanks for your replay. i can understand now.

CSql > i will use to Query in report or list.

CActive > very easy to implement in CRUD data.

this is just sample when i get data from sql:

public function getCustomerList(){

$sql ="SELECT a.*,b.name as groupname

FROM `customer` as a

left join customer_group as b

on a.customer_group_id = b.customer_group_id";

$count = Yii::app()->db->createCommand('select COUNT(*) from customer')->queryScalar();

//make sql data provider

$dprov = new CSqlDataProvider($sql,array(











return $dprov;


How can I show the result of getCustomerList() function into a zii.widgets.grid.CGridView?

I have tried this code:

$dataProvider = getCustomerList();

$this->widget('zii.widgets.grid.CGridView', array(




but i see this error:

[font=Verdana][size=2]Undefined index: id[/size][/font]




Can You help me? How can I show SQL result into a zii.widgets.grid.CGridView?

I have solved,

I had copied bad the source code

You have to configure ‘keyField’ attribute to specify the key column that identifies the row in the results set.

It defaults to ‘id’, and usually we don’t have to explicitly configure it.

But if you don’t have ‘id’ column in your result sets, you have to.