Quantcast
Channel: Yii Framework Forum
Viewing all articles
Browse latest Browse all 18717

Proper Way To Related Models And Preform Db Queries

$
0
0
Hello all,


I'm pretty confused on what I am doing wrong.

I have a view duplicating a db query every record.

How could I get this to stop doing this?

Also, is there a way I could join the first 2 calls into one?


here is the log


0.00028 ms system.db.CDbCommand.query(SELECT COUNT(*) FROM `companies` `t`)

0.00041 ms system.db.CDbCommand.query(SELECT * FROM `companies` `t` ORDER BY name ASC LIMIT 50)

The next one repeats/duplicates for every record


0.00030 ms system.db.CDbCommand.query(SELECT `country0`.`id` AS `t1_c0`, `country0`.`name` AS `t1_c1`, `country0`.`abbreviation` AS `t1_c2` FROM `country` `country0` WHERE (`country0`.`id`=:ypl0). Bound with :ypl0='1')


Model

	public function relations()
	{ 
		return array(
                        .......
			'country0' => array(self::BELONGS_TO, 'Country', 'country'),
		);
	}

	
	public function search()
	{
		$criteria=new CDbCriteria;
                 .....
		$criteria->compare('country',$this->country);
			return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
			'pagination'=>array(
                        'PageSize'=>50),
			'sort'=>array(
				'defaultOrder'=>'name ASC',
			),
		));
	}


view

<?php $this->widget('zii.widgets.grid.CGridView', array(
	.......
        'dataProvider'=>$model->search(),
        'filter'=>$model,
	'columns'=>array(		
		....
		array(
			'name'=>'country',
			'type'=>'raw',
			'value' => '$data->country0->abbreviation', 
		),
		
	),
)); ?>




Controller


<?php

class CompaniesController extends Controller
{
	//renders the view
	public function actionList()
	{
		$model = new Companies;
		
		$dataProvider=new CActiveDataProvider('Companies');
		$this->render('companylist',array(
			'dataProvider'=>$dataProvider,
			'model' => $model,
		));
	}

	public function loadModel($id)
	{
		$model=Companies::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}



Viewing all articles
Browse latest Browse all 18717

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>