在laravel中标记更新的多对多关系复选框

tf7tbtn2  于 2023-05-08  发布在  其他
关注(0)|答案(1)|浏览(127)

我正试图显示从多对多关系中获取的已更新复选框。
型号Candidato

public function estados()
    {
        return $this->belongsToMany(EstadoPostulacion::class, 'candidato_estado_postulacions', 'status_id', 'user_id')->withTimestamps();        
    }

型号EstadoPostulacion

public function candidatos()
    {
        return $this->belongsToMany(Candidato::class,  'candidato_estado_postulacions','user_id', 'status_id')->withTimestamps();
    }

型号CandidatoEstadoPostulacion

public function candidatos()
{
    return $this->hasMany(Candidato::class,  'status_id', 'user_id');
}

public function estados()
{
    return $this->hasMany(EstadoPostulacion::class, 'id', 'status_id');
}

控制器Candidatos

public function index( Vacancy $vacante, Candidato $candidato )
{
    $estados = EstadoPostulacion::pluck('status', 'id');

    $ca = Candidato::with('estados')->get();

    return view('candidatos.index', compact('vacante', 'estados', 'candidato') );
}

Candidatos
| 身份证|用户ID|空位ID|
| --------------|--------------|--------------|
estado_postulaciones
| 身份证|地位|
| --------------|--------------|
candidato_estado_postulaciones
| 状态ID|用户ID|空位ID|
| --------------|--------------|--------------|
查看candidatos/index.blade.php

@forelse ($estados as $id => $estado)
     <div>
          <input type="checkbox" name="status[]" id="{{ $estado }}-{{ $candidato->user_id }}" class="peer hidden" value="{{ $id }}" {{ $candidato->estados->contains($id) ? 'checked' : '' }} onchange="this.form.submit()">
          <label for="{{ $estado }}-{{ $candidato->user_id }}" class="block cursor-pointer select-none rounded-xl p-2 text-center peer-checked:bg-blue-500 peer-checked:font-bold peer-checked:text-white">
          <i class="fas fa-folder fa-2x"></i>
          <div class="w-full text-xs">Está en:</div>
          <div class="w-full text-xs text-gray-800 font-semibold uppercase">{{ $estado }}</div>
          </label>
   </div>
   @empty
      <li>No existe ningun estado en la BD</li>
   @endforelse

我需要它显示的图像:

uyto3xhc

uyto3xhc1#

我不明白 belongsToMany 是否是 CandidatoEstadoPostulacion 之间的正确关系,可能是因为一些翻译问题。我认为你还应该创建一个模型 Status 和一个表 statuses,所以,代替$estados = EstadoPostulacion::pluck('status', 'id');,你可以用Status::all()(或类似的东西)来获取状态。
您的具体问题是您在视图中使用了$candidato->estados->contains($id) ? 'checked' : '',但是由于 estados 是一个 belongsToMany 关系,它返回一个 collection containing models,因此它永远不会包含等于 $id 的元素,并且该表达式将永远是 false。还要注意,类Model不拥有名为contains()的方法。
无论如何,我认为最接近实现你想要的东西是这样的:

$candidato->estados()->whereId($id)->exists() ? 'checked' : ''

更新

考虑到@miken32的评论,一个更好的选择可能是在 estados 集合上使用 where 过滤器:

$candidato->estados->where('id', $id)->count() ? 'checked' : ''

相关问题