我有两个不同的表,center
和student
在第一个表Center
中,我有c enter_id
列。在该表中,我有center_id,例如“ PP_123”。
在第二个表student
中,创建了center_code
列。在该表中,我保存的是“ PP_123”之类的center_code。
如果中心用户将该学生的第二时间表student
文件与学生数据一起注册,并且将center_code
存储在student
表中。
中心表数据所有中心列表
scenter_name Date of join center_code
HALO COMPUTERS 02-12-2019 PP_123
scenter_name Date of join center_code
SKILL EDUCATION CENTER 02-12-2019 PP_123
学生表数据所有注册的学生列表
student_name student_f_name student_m_name center_code
abc abc abc PP_123
student_name student_f_name student_m_name center_code
xyz xyz xyz PP_123
student_name student_f_name student_m_name center_code
vvv vvv vvv PP_124
视图应显示如下结果
CENTER CODE DATE OF JOIN CENTER NAME APPLICATION COUNT
PP_123 02-12-2019 HALO COMPUTERS 2
PP_124 10-12-2019 SKILL EDUCATION CENTER 1
Controller [此代码仅显示所有中心名称和ID]
public function center_activities()
{
$activities_list =
return view('Center.cernter_activites',compact('activities_list'));
}
我的看法
<table class="table table-striped table-bordered table-hover dataTables-example">
<thead>
<tr>
<th>SL,no</th>
<th>CENTER CODE</th>
<th>DATE OF JOIN</th>
<th>CENTER NAME</th>
<th> APPLICATION count</th>
</tr>
</thead>
<tbody>
<tr >
<td>{{ $key + 1 }}</td>
<td>{{ $activities_list->center_code }}</td>
<td>{{ $activities_list->center_join_date }}</td>
<td>{{ $activities_list->center_name }}</td>
<td>0</td>
</tr>
</tbody>
</table>
我的模型与一对一的关系
Center.php模型
public function student()
{
return $this->hasOne('App\Student', 'center_code');
}
Student.php模型
public function center()
{
return $this->belongsTo('App\Center', 'center_code');
}
建立应用程序学生与中心之间的关系。
并建立变种器以计算学生人数。
在您的Center.php
模型中:
public function students()
{
return $this->hasMany(App\Student::class, 'center_id', 'center_id');
}
public function getApplicationCountAttribute()
{
return $this->students()->count();
}
$activities_list = Center::where('center_delete','NOT-DELETED')->Where('account_type','OLD_ACCOUNT')->get();
return view('Center.cernter_activites',compact('activities_list'));
在您看来,您可以循环列表并轻松获得计数。
@foreach ($activities_list as $activity)
...
{{ $activity->application_count }}
@endforeach
假设您要获取所搜索中心的所有学生的计数,则应该可以使用withCount
来获取每个中心的相关记录的计数。尝试如下设置:
中心型号:
public function students()
{
return $this->hasMany(Student::class, 'center_code', 'center_code');
}
控制器:
$centers = Center::where('center_delete', 'NOT-DELETED')
->where('account_type', 'OLD_ACCOUNT')
->withCount('students')
->get();
查看:
@foreach ($centers as $center)
...
<td>{{ $center->students_count }}</td>
...
@endforeach
Laravel 5.7 Docs - Eloquent - Relationships - Counting Related Records withCount
使用count()
public function center_activities()
{
$activities_list = Center::where('center_delete','NOT-DELETED')->Where('account_type','OLD_ACCOUNT')->count();
return view('Center.cernter_activites',compact('activities_list'));
}