Reputation: 531
I want to count each center users how mach student they registered.
I have two different table, center
and student
In first table Center
, I have center_id
column. In that table I have center_id like "PP_123".
In second table student
I was created center_code
column. In that table I am saving center_code like "PP_123".
If center user registers student that time second table student
files with student data along with it stores the center_code
in student
table.
center table data ALL CENTERS LIST
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 table data ALL REGISTERED STUDENT LIST
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
view should show result like below
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 [This code only showing all centers name and id]
public function center_activities()
{
$activities_list =
return view('Center.cernter_activites',compact('activities_list'));
}
my view
<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>
my model with relationship one to one
Center.php model
public function student()
{
return $this->hasOne('App\Student', 'center_code');
}
Student.php model
public function center()
{
return $this->belongsTo('App\Center', 'center_code');
}
Upvotes: 1
Views: 257
Reputation: 50491
Assuming you want to get a count of all the students for the centers you are searching for, you should be able to use withCount
to get a count of the related records for each center. Try setting up things as below:
Center Model:
public function students()
{
return $this->hasMany(Student::class, 'center_code', 'center_code');
}
Controller:
$centers = Center::where('center_delete', 'NOT-DELETED')
->where('account_type', 'OLD_ACCOUNT')
->withCount('students')
->get();
View:
@foreach ($centers as $center)
...
<td>{{ $center->students_count }}</td>
...
@endforeach
Laravel 5.7 Docs - Eloquent - Relationships - Counting Related Records withCount
Upvotes: 1