Yii2:如何从模型中获取返回值? [英] Yii2:how to get return value in view from model?
本文介绍了Yii2:如何从模型中获取返回值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个表名staff".Staff表和考勤表是一对多的关系.
I have a table name "staff".Staff table has one to many relation with attendance table.
在模型 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 和 $leave 的返回值.
使 GoogleChart 动态化.如何在yii2视图中回显模型的函数返回值?
i want to get the returned value of $present ,$Absent and $leave.
to make GoogleChart dynamic. How to echo the function returned value from model in view in yii2 ?
推荐答案
我觉得你应该使用静态函数
I think you should use static function
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;
}
以及在您的小部件中的使用
and the use in your widget
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()],
],]);
?>
这篇关于Yii2:如何从模型中获取返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文