Laravel 尝试从数据透视表获取数据 table

Laravel trying to get data from the pivot table

我正在尝试从枢轴table(多对多关系)中获取链接到我的模型的数据。 我让客户与部门建立多对多关系。

迁移:

Schema::create('customer_department', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->unsignedBigInteger('customer_id');
            $table->unsignedBigInteger('department_id');
            $table->timestamps();

            $table->foreign('customer_id')
                ->references('id')
                ->on('customers');

            $table->foreign('department_id')
                ->references('id')
                ->on('departments');
        });

客户模型:

public function department(){
    return $this->belongsToMany('App\Department');
}

部门模型:

public function customer(){
    return $this->belongsToMany('App\Customer');
}

现在我正在尝试在视图中打印出客户被分配到的每个部门。我试过了

{{$customer->department}}
or
@foreach($customer->department as $depo)
{{$depo->name}}
@endforeach
or
{{$customer->pivot->department_id}}
...

控制器:

public function show(Customer $customer)
    {
        return view('/customers/customer', ['customer' => $customer]);
    }

但是我收到几条错误消息、空数组或什么都没有。我究竟做错了什么?我忘记了什么?

您必须通过多对多关系检索模型才能附加此 pivot 模型。 $customer 不会有这个 pivot,但是从 $customer->department 编辑的所有 return 都会附加这些 pivot 模型:

@foreach ($customer->department as $department)
    {{ $department->pivot->department_id }}
@endforeach

不过,在这种情况下,您不需要涉及数据透视模型,因为您需要来自部门模型的信息:

@foreach ($customer->department as $department)
    {{ $department->getKey() }}
    {{ $department->name }}
@endforeach

最好用复数命名这些关系,因为它们 return 很多,而不是单数。