如何从 Laravel 中的 HasManyThrough 与数据透视表的关系中获取计数

问题描述 投票:0回答:1

我想统计一下有多少候选人参加比赛。

我有4张桌子:

比赛

  • id
  • 名字
  • 来自
  • 直到

空缺

  • id
  • 竞赛_id
  • 名字
  • 描述

用户

  • id
  • 名字

数据透视表:

用户_空缺

  • id
  • 用户ID
  • 职位空缺_id

我的比赛模型

protected $fillable = [
        'name',
        'from',
        'until',
        'description',
    ];

public function vacancies()
    {
        return $this->hasMany(Vacancy::class);
    }

public function candidates()
    {
        return $this->hasManyThrough(User::class, Vacancy::class);
    }

我的空缺模型

public function contest()
    {
        return $this->belongsTo(Contest::class);
    }

public function candidates()
    {
        return $this->belongsToMany(User::class, 'user_vacancy');
    }

我的用户模型

public function vacancies()
    {
        return $this->belongsToMany(Vacancy::class, 'user_vacancy');
    }

我的控制器

public function index()
    {
        $contests = Contest::with('vacancies.candidates')
            ->get();

        return view('contests.index', compact('contests'));
    }

我收到此错误:

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

当我这样做时:

@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
laravel pivot-table has-many-through
1个回答
0
投票

请将关系候选人的竞赛模型函数更新为以下

public function candidates()
{
   return $this->hasManyThrough(User::class, Vacancy::class, 'contest_id', 'vacancy_id', 'id', 'id');
}
© www.soinside.com 2019 - 2024. All rights reserved.