I want to export data to excel using 2 models. HasilPutusan model and DetilSaksi model.
When I used the CActiveDataProvider with Model HasilPutusan, I managed to get all the data together with the data relationships that are interrelated with this HasilPutusan models.
And how do I combine the data both by using Model DetilSaksi?
My controller :
public function actionCetakjalanperistiwa()
{
if(isset($_POST['PrintJaper'])){
$data = $_POST['id_kecelakaan'];
if($data==''){
return false;
}else{
$dataProvider=new CActiveDataProvider('HasilPutusan', array(
'criteria'=>array(
'condition'=>'id_kecelakaan=:id',
'params'=>array(':id'=>$data),
),
));
}
$this->widget('ext.EExcelView', array(
'grid_mode'=>'export',
'title' => 'Data Jalan Peristiwa',
'dataProvider' => $dataProvider,
'exportType'=>'Excel2007',
'columns'=>array(
'id_hasil_putusan',
'id_detil',
'id_kapal',
'idKapal.nama_kapal',
'idKapal.tahun_pembuatan',
'idKapal.konstruksi',
'idKapal.isi_kotor',
'idKapal.tenaga_penggerak_utama',
'idKapal.pemilik',
'idKapal.nakhoda',
'idKapal.awak_kapal',
'idKapal.surat_kapal',
),
));
}else{
$this->render('_japer');
}
}
In my tbl_hasil_putusan table, i have a id_detil field which I will use to re-do the query to the second table using the DetilSaksi model.
My database :
How do I combine the two tables that can be joined so that I can call related (blue arrow) data in the second table?
Thanks
You can use join in the criteria array. Something like this:
$dataProvider=new CActiveDataProvider('HasilPutusan', array(
'criteria'=>array(
'condition'=>'id_kecelakaan=:id',
'select' => 't.*, ds.*'
'join' => 'LEFT JOIN tbl_detil_saksi ds on ds.id_detil = t.id_detil',
'params'=>array(
':id'=>$data),
),
));
Related
I'm currently new to Yii and have some problems in my app.
I have 2 AR (Employee and Children) with the relations is Employee has_many Children. Now when we go into the view of Employee (in the view&id=blablabla not in index), I want to list all the children that the Employee have.
I have made a function in EmployeeController class to retrieve the children from my db
$anak = Anak::Model()->findAll(array(
'condition'=>'id_karyawan=:id_karyawan',
'params'=>array(':id_karyawan'=>$id_karyawan)));
//return $anak;
foreach ($anak as $data){
return $data->namaanak;
}
the problem is, it only showing 1 data (the first one, to be exact) of the children, even though in my db the Employee has 3 children. When I try to count of query result, it's showing 3.
My employee/view is like this
$this->widget('zii.widgets.CDetailView', array(
'data'=>$model,
'attributes'=>array(
'id_karyawan',
'nama',
array(
'name'=>'idjabatan',
'value'=>$model->findByPk($model->id_karyawan)->jabatan->namajabatan,
),
array(
'name'=>'gaji',
'value'=>Yii::app()->numberFormatter->formatCurrency($model->findByPk($model->id_karyawan)->jabatan->gaji, 'Rp'),
),
'alamat',
array(
'name'=>'ttl',
'value'=>$model->tempatlahir.', '.Yii::app()->dateFormatter->format("dd MMMM yyyy", $model->tgllahir),
),
array(
'name'=>'Istri',
'value'=>Istri::model()->getNama($model->id_karyawan),
'type'=>'raw'
),
array(
'name'=>'Anak',
'value'=>$this->getAnak($model->id_karyawan),
'type'=>'raw'
)
),
I have tried to google it, but i couldn't find any working answer :(
PS: karyawan = employee, anak = children.
You are only getting the first related value because you are returning it right away inside your foreach loop in the function. Gather all the related models first then return that and work with that data.
You can also skip that extra function inside your controller. If you use Gii, it should have already set up the proper Employee HAS_MANY children relation for you, so you could use that to pull all related models for each Employee model you are looking at. See below for a quick example
Employee model:
public function relations()
{
return array(
'children' => array(self::HAS_MANY, 'Child', 'employee_id'),
);
}
View file, passing an employee model to CDetailView:
$this->widget('zii.widgets.CDetailView', array(
'data' => $model,
'attributes'=>array(
array(
'name' => 'Children',
'value' => function ($data) {
// Get all related children using the relation defined in the Employee model and use CHtml::listData to store data inside the $children variable as an array using `id` as key and `child_name` as value
$children = CHtml::listData($data->children, 'id', 'child_name');
// Return names as a comma separated list
return implode(', ', $children);
},
'type'=>'raw'
)
)
);
My tables/column names probably don't match up with what you have but hopefully this helps.
I have an complex query with joins and conditions
and I get data with CSqlDataProvider
But I also need to join relational table records.
Lets say, we have table A (products) and table B (product_modifications)
I need to list products along with their modifications..
I get data from table A, and i need also to get some records from table B
for each record in table A, query should get an array from table B
Basic code:
class Product extends CActiveRecord
{
//some code
public function relations()
{
return array(
'modifications' => array(self::HAS_MANY, 'Modification', 'modification_product_id'),
);
}
//some code
}
my query
$sql = Yii::app()->db->createCommand();
...//different joins and conditions
$this->dataProvider = new CSqlDataProvider($sql->text, array(
'keyField' => 'product_id',
'pagination' => array('pageSize' => 20),
));
How can i join records from table B (product_modifications)?
In CActiveDataProvider its like:
$this->dataProvider = new CActiveDataProvider ('products', array(
'pagination' => array('pageSize' => 20),
'criteria' => array(
'with' => array(
'modifications' => array('condition' => 'some condition',),
),
),
));
But i dont know how to do this with CSqlDataProvider
UPD:
solved by converting query to corresponding CActiveDataProvider query
You can't use AR-relation with sql commands, because it is absolutely different tools for work with Db. In ActiveRecord you are using relation, in Sql commands you are using sql-joins. That's mean you should add you condition there with join:
$sql = Yii::app()->db->createCommand();
...//different joins and conditions + your condition
How can I display "arrendatario_nombre" using a dataprovider in a Clistview
$dataProviderContratos = new CActiveDataProvider(ZfContratos::model(), array(
'keyAttribute'=>'zf_contrato_id',
'criteria'=>array(
'order' => 'contrato_fecha_ini',
'select' => 't.*, arr.arrendatario_nombre as arrendatario_nombre',
'join' => 'LEFT JOIN zf_arrendatarios arr ON arr.arrendatario_id = t.zf_arrendatarios_arrendatario_id',
'condition'=>'zf_inmuebles_inmueble_id=-1',
),
));
I tried:
$data->arrendatario_nombre
Thanks!
You can use Yii relations for this purpose,
http://www.yiiframework.com/doc/guide/1.1/en/database.arr#declaring-relationship
In your ZfContratos model file use the following and then you can call $data->arrendatario_nombre
public function relations() {
return array(
'arrendatario_nombre' => array(self::BELONGS_TO, 'zf_arrendatarios', 'zf_arrendatarios_arrendatario_id'),
);
}
Once this is declared in the model file you can use $data->arrendatario_nombre and also in any other place place you load the Zfcontratos model
I'm getting foreign key relation based display ids in the gridviews. How to get values instead of ids? Code in my gridview is following:
$criteria->compare('education.UniversityNameid',$this->UniversityName, true);
my gridviews inside code
array(
'name' => 'UniversityName',
'type' => 'raw',
'value'=>'(empty($data->education->UniversityNameid))? "" : Yii::app()->params["currencySymbol"]." ".$data->education->UniversityNameid',
),
You have to set up a relation in your model "University" like this
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(
'UniversityName' => array(self::BELONGS_TO, 'University', 'UniversityNameid'),
);
}
thank you can access the Name
$data->education->UniversityName
Set the relation in your model like
'u' => array(self::BELONGS_TO, 'University', 'UniversityNameid'),
and acess it like
'attributes'=>array(
array('name'=>'u.UniversityName',
'label'=>'University',),
),
Suppose I have model User which have many to many relation to itself named as friends.
so $user->friends (or $model->friends in view) gives me an array of User objects. I wanted to display the friends as gridview. But CGridView data as dataProvider object. Googling for it found the way to convert array of model objects to dataProvider object as given below.
$this->widget('zii.widgets.grid.CGridView', array(
'id' => 'gridUser',
'dataProvider' => new CArrayDataProvider($model->friends, array()),
));
Now using this I get an error
Property "User.id" is not defined.
UPDATE
public function relations()
{
return array(
'friends' => array(self::MANY_MANY, 'User', 'friendship(user_id, friend_id)'),
);
}
I use two stage building the provider shown below. But I found that it gives you trouble in terms of Pagination. I have not bothered to resolve that problem since am doing other things
$dataProvider = new CArrayDataProvider('User');
$dataProvider->setData($model->friends);
$this->widget('zii.widgets.grid.CGridView', array(
'id' => 'gridUser',
'dataProvider' =>$dataProvider,
));
That being said, your code should work (see the example below from API docs). I suspect there is wrong attribute in your relations than the provided code. Re-check the relation definition if it is ok
From Yii docs:
$rawData=Yii::app()->db->createCommand('SELECT * FROM tbl_user')->queryAll();
// or using: $rawData=User::model()->findAll(); <--this better represents your question
$dataProvider=new CArrayDataProvider($rawData, array(
'id'=>'user',
'sort'=>array(
'attributes'=>array(
'id', 'username', 'email',
),
),
'pagination'=>array(
'pageSize'=>10,
),
));
Got it :) , i can use CActiveDataProvider instead of CArrayDataProvider as given below
$this->widget('zii.widgets.grid.CGridView', array(
'id' => 'gridUser',
'dataProvider' => new CActiveDataProvider('User', array(
'data'=>$model->friends,
)),
//...... columns display list.....
));
Anyways thanks for the reply #Stefano