i'm using findBySql() to get data from database, i want to show the data in view with table.
This is code on my controller :
$sql = "SELECT presensi.presensi_tanggal 'tanggal', sum(if( hadir.keteranganhadir_id='1',1,0)) 'hadir', sum(if( hadir.keteranganhadir_id='2',1,0)) 'tidak_hadir', count(*) 'total' FROM hadir, keteranganhadir, presensi where hadir.keteranganhadir_id = keteranganhadir.keteranganhadir_id and hadir.presensi_id = presensi.presensi_id group by presensi.presensi_tanggal";
$model = Hadir::findBySql($sql)->all();
return $this->render('index', [
'hadir' => $model,
]);
So, i want to show 'tanggal', 'hadir', 'tidak hadir' and 'total'.
In my view,
<?php foreach($hadir as $data): ?>
<tr>
<td></td>
<td class="tbl_column_name"><?=$data->tanggal;?></td>
<td class="tbl_column_name"><?=$data->hadir;?></td>
<td class="tbl_column_name"><?=$data->tidak_hadir;?></td>
<td class="tbl_column_name"><?=$data->total;?></td>
<td><a href="kehadiran/view?id=1">Lihat</a></td>
</tr>
<?php endforeach; ?>
But, i got error like this Unknown Property – yii\base\UnknownPropertyException Getting unknown property: common\models\data\Hadir::tanggal. So, what is the problem and what should i do? Thank you~
[EDITED]
Hadir Model :
<?php
namespace common\models\data;
use Yii;
/**
* This is the model class for table "hadir".
*
* @property integer $ADIKBINAAN_ID
* @property integer $PRESENSI_ID
* @property integer $KETERANGANHADIR_ID
*
* @property Adikbinaan $aDIKBINAAN
* @property Presensi $pRESENSI
*/
class Hadir extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'hadir';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['ADIKBINAAN_ID', 'PRESENSI_ID', 'KETERANGANHADIR_ID'], 'required'],
[['ADIKBINAAN_ID', 'PRESENSI_ID', 'KETERANGANHADIR_ID'], 'integer']
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'ADIKBINAAN_ID' => 'Adikbinaan ID',
'PRESENSI_ID' => 'Presensi ID',
'KETERANGANHADIR_ID' => 'Keteranganhadir ID',
];
}
/**
* @return \yii\db\ActiveQuery
*/
public function getADIKBINAAN()
{
return $this->hasOne(Adikbinaan::className(), ['ADIKBINAAN_ID' => 'ADIKBINAAN_ID']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getPRESENSI()
{
return $this->hasOne(Presensi::className(), ['PRESENSI_ID' => 'PRESENSI_ID']);
}
}
By default the attributes that are extracted from the returned rows are only the columns that can be found in the table.
I get the impression from your code that those fields are not. To fix this you should probably override the attributes()
-function and declare those properties as valid:
public function attributes()
{
return array_merge(parent::attributes(), ['tanggal', 'hadir', 'tidak_hadir', 'total']);
}
This should instruct the populateRecord()
-function to also fill those.