How To Make True Hungry Load For Cgridview/cactiveprovider

i almost got how make hungry load in CActiveProvider. this code removes N loads of relational tables




//controllers/NotesController.php


	public function actionGetNotes()

	{

		$dp_notes = new CActiveDataProvider('Notes');

		$dp_notes->setCriteria((new CDbCriteria(['with' => ['tempo','genre']])));

		$filter_note = new Notes('filter');


		$this->render('list', [

			'dp_notes' => $dp_notes,

			'filter_note' => $filter_note

		]);

	}




//views/notes/list.php


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

    'id' => 'notes-grid',

    'dataProvider' => $dp_notes,

    'filter' => $filter_note,

    'columns' => [

        'note_id',

        'title',

		'bpm',

        ['name' => 'genre', 'value' => '$data->genre->name'],

		['name' => 'tempo', 'value' => '$data->tempo->name'],

        'created_date'

    ],

    'htmlOptions' => [

        'style' => 'cursor: pointer;'

    ],

 //   'selectionChanged' => 'function(id){showNote($.fn.yiiGridView.getSelection(id));}'

]);

?>



but i still have some strange sql queries




SELECT COUNT(DISTINCT `t`.`note_id`) FROM `Notes` `t` LEFT OUTER JOIN `Tempos` `tempo` ON (`t`.`tempo_id`=`tempo`.`tempo_id`) LEFT OUTER JOIN `Genres` `genre` ON (`t`.`genre_id`=`genre`.`genre_id`) )




SELECT `tempo`.`tempo_id` AS `t1_c0`, `tempo`.`name` AS `t1_c1`, `tempo`.`explain` AS `t1_c2` FROM `Tempos` `tempo` WHERE (`tempo`.`tempo_id`=:ypl0). Bound with :ypl0=NULL)


SELECT `genre`.`genre_id` AS `t1_c0`, `genre`.`name` AS `t1_c1` FROM `Genres` `genre` WHERE (`genre`.`genre_id`=:ypl0). Bound with :ypl0=NULL)



relations are next




//models/Notes.php


	public function relations()

	{

		return [

			'genre' => [self::BELONGS_TO, 'Genres', 'genre_id'],

			'tempo' => [self::BELONGS_TO, 'Tempos', 'tempo_id']

		];

	}



regards

p.s.

i guess they come from $filter_note but how can i avoid these 3 requests?

p.p.s yes, it’s filter in CGridView…

The first query comes from the grid, which needs to know the total number of elements. You can compute it yourself and pass to the grid, so it won’t be fetched from the db.

Other queries look a bit strange, it’s like something tries to read relations by accessing a new (unsaved) model properties. Active data provider uses only a static model, so maybe it’s the filter? Maybe you got columns named as relations and the grid tries to read the filter’s values for them. Try assigning null values to them after creating the filter model, like this:




$filter_note = new Notes('filter');

$filter_note->genre = null;

$filter_note->tempo = null;



nineinchnick,

thank you. you are 100% right, it works like a charm