[英]Laravel trying to get data from the pivot table
我試圖從 pivot 表中獲取鏈接到我的 model 的數據(多對多關系)。 我讓客戶與部門建立多對多的關系。
遷移:
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');
});
客戶 model:
public function department(){
return $this->belongsToMany('App\Department');
}
部門model:
public function customer(){
return $this->belongsToMany('App\Customer');
}
現在我試圖在視圖中打印出客戶分配到的每個部門。 我試過了
{{$customer->department}}
or
@foreach($customer->department as $depo)
{{$depo->name}}
@endforeach
or
{{$customer->pivot->department_id}}
...
controller:
public function show(Customer $customer)
{
return view('/customers/customer', ['customer' => $customer]);
}
但是我收到幾條錯誤消息,空的 arrays 或什么都沒有。 我究竟做錯了什么? 我忘了什么?
您必須通過多對多關系檢索 model 才能使其附加pivot
model。 $customer
不會有這個pivot
但是從$customer->department
返回的所有東西都會附加這些pivot
模型:
@foreach ($customer->department as $department)
{{ $department->pivot->department_id }}
@endforeach
不過,在這種情況下,您不需要涉及 pivot model 因為您需要來自部門模型的信息:
@foreach ($customer->department as $department)
{{ $department->getKey() }}
{{ $department->name }}
@endforeach
將這些關系命名為復數是個好主意,因為它們返回很多,而不是單數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.