【问题标题】:How can I make list of values that aren't in pivot table?如何列出不在数据透视表中的值?
【发布时间】:2019-04-04 15:54:03
【问题描述】:

我正在尝试列出不在数据透视表中的值。

表格是 Participantes 和 Eventos(参与者和事件)。

这将返回数据透视表中的所有参与者。

@foreach ($evento->participantes as $participante)

        <tr value="">
        <td >{{$participante->nombre}}</td>
        <td>{{$participante->apellidos}}</td>
        <td>{{$participante->sexo}}</td>
        <td>{{$participante->categoria->nombre}}</td>
        <td>{{\Carbon\Carbon::parse($participante->fecha_nacimiento)->age}}</td>
        <td>{{$participante->club->nombre}}</td>
        <td>{{$participante->cinturon}}</td>
        <td><input type="checkbox" name="id_participante[]" value="{{$participante->id_participante}}"/></td>
        </tr>
@endforeach

我认为使用 in_array()。所以我尝试了

@foreach ($participantes as $participante)
    @if(in_array($participante,$evento->participante))

但是 "$evento->participant" 不是数组,所以我尝试了 ->toArray().. 但它不起作用。

我的 Evento 模型使用“参与者方法”:

class Evento extends Model
{


    protected $primaryKey = 'id_evento';

    public function participantes(){

        return $this->belongsToMany('App\Participante', 'evento_participante', 'id_evento', 'id_participante' );

    }

}

谢谢,对不起我的英语。

【问题讨论】:

  • 能否请您发布您的模型方法参与者?
  • 当然。 OP 已编辑。

标签: laravel list foreach pivot-table


【解决方案1】:

relations 基本上返回一个集合数据类型。因此,您可以使用各种收集方法而不是循环遍历关系,这不是优化查询的最佳方法。查看文档链接https://laravel.com/docs/5.8/collections

  // find the event 
        $event  = Event::find(1);
        $participant_ids =  $event->participants->pluck('pivot.participant_id')->toArray();

        //finding participants who are not in event
        $not_in_event = Participant::whereNotIn('id',$participant_ids)->get();

        return $not_in_event;

【讨论】:

    猜你喜欢
    • 2020-05-05
    • 2017-02-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-26
    • 1970-01-01
    • 2017-10-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多