我有一个表名“staff”.Staff表与考勤表有一对多的关系。
在模型Staff.php
public function getAttendances()
{
if(isset($_GET['startdat']))
$start_date=$_GET['startdat'];
if(isset($_GET['enddate']))
$end_date=$_GET['enddate'];
if(isset($_GET['startdat'])){
return $this->hasMany(Attendance::className(), ['staff_id' => 'id'])
->where('daytime >= "'.$start_date.'" and daytime<="'.$end_date.'"');
}
else{
return $this->hasMany(Attendance::className(), ['staff_id' => 'id'])
->andOnCondition(['daytime' => 'Absent'])
->orOnCondition(['status' => 'Present'])
->orOnCondition(['status' => 'leave']);
}
}
public function getPresent(){
$present=0;
foreach($this->attendances as $attendance){
if($attendance->status=='Present')
$present++;
}
return $present;
}
public function getAbsent(){
$Absent=0;
foreach($this->attendances as $attendance){
if($attendance->status=='Absent')
$Absent++;
}
return $Absent;
}
public function getLeave(){
$Leave=0;
foreach($this->attendances as $attendance){
if($attendance->status=='Leave')
$Leave++;
}
return $Leave;
}
在观看 report.php
中<?=
GoogleChart::widget(['visualization' => 'PieChart',
'data' => [
['Task', 'Hours per Day'],
['Present', 5],
['Absent', 2],
['leave', 4],
],]);
?>
我希望获得$present ,$Absent and $leave.
的返回值,以使GoogleChart动态化。如何在yii2中查看模型中的函数返回值?
答案 0 :(得分:0)
您可以尝试使用此代码从模型函数中获取价值。
use path\to\model\Staff;
<?=
GoogleChart::widget(['visualization' => 'PieChart',
'data' => [
['Task', 'Hours per Day'],
['Present', Staff::getPresent()],
['Absent', Staff::getAbsent()],
['leave', Staff::getLeave()],
],]);
?>
答案 1 :(得分:0)
我认为你应该使用静态功能
public static function getAttendances()
{
.......
public static function getPresent(){
$present=0;
foreach(self::attendances() as $attendance){
if($attendance->status=='Present')
$present++;
}
return $present;
}
public static function getAbsent(){
$Absent=0;
foreach(self::attendances() as $attendance){
if($attendance->status=='Absent')
$Absent++;
}
return $Absent;
}
public static function getLeave(){
$Leave=0;
foreach(self::attendances() as $attendance){
if($attendance->status=='Leave')
$Leave++;
}
return $Leave;
}
以及在小部件中的使用
use path\to\model\Staff;
<?php echo GoogleChart::widget(['visualization' => 'PieChart',
'data' => [
['Task', 'Hours per Day'],
['Present', Staff::getPresent()],
['Absent', Staff::getAbsent()],
['leave', Staff::getLeave()],
],]);
?>