if we have 2 table or more you can joined easily, but in Yii we must create relationship before using it.
Howto
1. Setup Relation
i have 2 Table with spec :
- table 1 name : Yiitest
field : 1. id [PK]
2. name
3. Description
-----Join table using field name ------
- table 2 name : Yiitest2
field : 1. name [PK]
2. position
* Case : i need join table Yiitest to Yiitest2, and Yiitest.name based on Yiitest2.name[PK]
How we do that ?? just create relationship
Go to your model Yiitest and add this code line
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
'Yiitest2'=> array(self::BELONGS_TO,'Yiitest2','name'),
);
}
* Relation have been create, now we can query using CActiveDataProvider
2. Query Join with CActiveDataProvider
Controller :
$dataProvider = new CActiveDataProvider('Yiitest',array(
'criteria'=>array('join'=>'right join yiitest2 x on x.name =
t.name',
'order' => 'id'),
'pagination'=>array('pageSize'=>2),));
// send object to view
$this->render('your_view', array('dataProvider' => $dataProvider));
*look at red mark, because we use join that model using alias 't' (by default Yii).
3. Display Using CGridView with Join Field and Pagination
View :
<?php
$this->widget('zii.widgets.grid.CGridView', array(
'dataProvider'=>$dataProvider,
'columns'=>array('name','description','Yiitest2.position'),
'pager'=>array(
'class'=>'CLinkPager',
'header'=>'',
'prevPageLabel'=>'<',
'nextPageLabel'=>'>',
'firstPageLabel'=>'First',
'lastPageLabel'=>'Last',
),
'enablePagination' => true,));
?>
* look at cyan mark , Why Yiitest2 ? not Yiitest ? because field position in model Yiitest2 haha ,
simple right ?
* if you don't want pagination just change the value to false
1 comments:
Jayrajsinh Mahipatsinhji Jadeja
ReplyPost a Comment
Harap gunakan bahasa yang baik dan sopan, terima kasih