并且我使用此代码将数据从数据库提取到表中 在Controller中:
$TableB1 = \DB::table('users')
->join('group_user', 'users.id', '=', 'group_user.user_id')
->join('groups', 'groups.id', '=', 'group_user.group_id')
->select(
'users.name as name',
'group_user.user_id as id',
'groups.name as groupname'
)
->get();
$view->with('TableB1',$TableB1);
return $view;
在index.blade.php
<thead>
<tr>
<th>Team</th>
<th>Name</th>
<th>No. of Showing</th>
<th>No. of Follow up</th>
<th>New Lead</th>
<th>Personal Lead</th>
</tr>
</thead>
<tbody>
<?php
use Carbon\Carbon;
foreach ($TableB1 as $data){
echo
'<tr>
<th scope="row">'. $data->groupname .'</th>
<th scope="row">'. $data->name .'</th>';
// To extract the number of meetings done by each agent(owned_by_id) everyday
$meetings = \DB::table('meetings')
->where('company_id', 1)->where('owned_by_id', $data->id)
->where(DB::raw('DAY(created_at)'), Carbon::today()->day);
echo '<th scope="row">' . $meetings->count() . '</th>';
// To extract the number of calls done by each agent(owned_by_id) everyday
$calls = \DB::table('calls')
->where('company_id', 1)->where('owned_by_id', $data->id)
->where(DB::raw('DAY(created_at)'), Carbon::today()->day);
echo '<th scope="row">' . $calls->count() . '</th>';
// To extract the number of leads created by each agent(owned_by_id) everyday
$leads = \DB::table('leads')
->where('lead_status_id', 1)->where('company_id', 1)->where('owned_by_id', $data->id)
->where(DB::raw('DAY(created_at)'), Carbon::today()->day);
echo '<th scope="row">' . $leads->count() . '</th>';
}
?>
</tr>
</tbody>
如何将php刀片中的代码移动到控制器?
该代码有效,但我认为该代码应该在控制器中正确吗?
并且如果可能的话,有一种方法可以通过AJAX按月份和年份过滤表中的数据,所以我不必刷新页面?
我正在使用Laravel 5.7
答案 0 :(得分:0)
在您的控制器中,您可以执行以下操作:
// $TableB1 = ...
// note the & in &$entry.
// The & makes $entry writable in the loop (to say it simply)
foreach ($TableB1 as &$entry){
$entry->meetingCount = (
\DB::table('meetings')
->where('company_id', 1)->where('owned_by_id', $data->id)
->where(DB::raw('DAY(created_at)'), Carbon::today()->day)
)->count();
// $entry->callCount = ...
// $entry->leadCount = ...
}
// $view->with('TableB1',$TableB1);
可以通过直接在SQL中包含所有计数来避免此循环,但是无论如何,让我们继续。
现在,您可以在视图中简单地做到这一点:
'<tr>
<th scope="row">'. $data->groupname .'</th>
<th scope="row">'. $data->name .'</th>';
<th scope="row">'. $data->meetingCount .'</th>';
<th scope="row">'. $data->leadCount .'</th>';
...
奖金:既然您使用Laravel和Blade,为什么不使用其语法?
<tbody>
@foreach($table as $entry)
<tr>
<th scope="row">{{$entry->groupname}}</th>
<th scope="row">{{$entry->name}}</th>
<th scope="row">{{$entry->meetingCount}}</th>
</tr>
@endforeach
</tbody>
不需要<?php
语句和大量引号。