I want to count how many candidates contest has.
I have 4 tables:
CONTEST
- id
- name
- from
- until
VACANCY
- id
- contest_id
- name
- description
USER
- id
- name
pivot table:
USER_VACANCY
- id
- user_id
- vacancy_id
My Contest model
protected $fillable = [
'name',
'from',
'until',
'description',
];
public function vacancies()
{
return $this->hasMany(Vacancy::class);
}
public function candidates()
{
return $this->hasManyThrough(User::class, Vacancy::class);
}
My Vacancy model
public function contest()
{
return $this->belongsTo(Contest::class);
}
public function candidates()
{
return $this->belongsToMany(User::class, 'user_vacancy');
}
My User model
public function vacancies()
{
return $this->belongsToMany(Vacancy::class, 'user_vacancy');
}
My Controller
public function index()
{
$contests = Contest::with('vacancies.candidates')
->get();
return view('contests.index', compact('contests'));
}
I got this error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'users.vacancy_id' in 'on clause'
select
count(*) as aggregate
from
`users`
inner join `vacancies` on `vacancies`.`id` = `users`.`vacancy_id`
where
`vacancies`.`contest_id` = 2
When I do this:
@foreach($contests as $contest)
<tr>
<td>1</td>
<td>{{ $contest->name }}</td>
<td>{{ date('d.m.Y', strtotime($contest->from)) }}</td>
<td>{{ date('d.m.Y', strtotime($contest->until)) }}</td>
<td>{{ $contest->vacancies()->count() }}</td>
{{-- TODO: Topshirilgan xujjatlar sonidan kelib chiqib Nomzodlar soni shaklanadigan qilish kerak --}}
<td>{{ $contest->candidates()->count() }}</td>
<td>75 ta</td>
@endforeach
2
Answers
Kindly update Contest model function of relationship candidate to the following
update the candidates relationship.
Controller
You can also use withCount with query but I kept your original code.
blade