向每个用户添加变量

时间:2015-02-27 11:27:27

标签: php laravel-4 foreach

基本上我尝试向每个用户添加一个变量(这是一个值),在这种情况下,该值显示需要为每个用户完成的计算,但不确定它是否正确以及如何在视图中获取该值:

控制器

    $users = User::all();
    foreach ($users as $user) {

        // Gets past events assigned to user
        $past_sessions = count(User::pastUserTraining($user->id)->get());
        // Gets past events attended 
        $amount_attended = count(User::amountTraingAttended($user->id)->get());

        // if no past events 
        if($past_sessions == 0){
            $res = 0;
        }
        else{
            $res = ($amount_attended / $past_sessions) * 100;
        }

        //Rounds number to whole number
        $res = round($res);
    }

    // load the view and pass the users with pes(value for each)
    return View::make('attendance.index')
               ->with('users', $users)
               ->with('pes', $res);
}

查看

@foreach($users as $key => $value)
    <tr class="users">
    <td>{{ ucfirst($value->firstName), ' ', ucfirst($value->lastName) }}</td>
    <td>{{ $pes }}<td>
@endforeach

所以理论上我希望它能够与

一起回归

用户名,值

用户名,值

目前它返回

用户名,上次计算的所有用户的值相同,

我知道我的方法有效,因为我可以在同一页面上显示个人的计算

2 个答案:

答案 0 :(得分:0)

您可以使用Accessor以这种方式尝试;

用户模型

class User extends Eloquent {
    ...

    public function getPesAttribute(){
        // Gets past events assigned to user
        $past_sessions = count(self::pastUserTraining($this->id)->get());
        // Gets past events attended 
        $amount_attended = count(self::amountTraingAttended($this->id)->get());

        // if no past events 
        if($past_sessions == 0){
            return 0;
        }

        $res = ($amount_attended / $past_sessions) * 100;

        //Rounds number to whole number
        return round($res);
    }

    ...
}

然后在您的视图中,只需使用$value->pes;获取此数据。

然后你就可以摆脱控制器了。像这样;

$users = User::all();

// load the view and pass the users with pes(value for each)
return View::make('attendance.index')
           ->with('users', $users);

请注意:尚未经过测试。

答案 1 :(得分:0)

您可以在用户模型上进行此计算。

查看:

@foreach($users as $user)
    <tr class="users">
    <td>{{ ucfirst($user->firstName), ' ', ucfirst($user->lastName) }}</td>
    <td>{{ $user->attendedRatio() }}<td>
@endforeach

在用户模型上,您可以

public function attendedRatio() {
    // Gets past events assigned to user
    $past_sessions = User::pastUserTraining($this->id)->count();
    // Gets past events attended 
    $amount_attended = User::amountTraingAttended($this->id)->count();

    // if no past events 
    if($past_sessions == 0){
        return 0
    }

    $ratio = ($amount_attended / $past_sessions) * 100;

    //Rounds number to whole number
    return round($ratio);
}

更好的原因(更快)是使用Eloquent hasMany关系和访问计数来使用连接。但这是一个易于理解的解决方案