簡體   English   中英

laravel關系多對多

[英]laravel relationship many to many

在Laravel中,我與許多人有很多關系:


Invoice.php

class Invoice extends Model {
     public function items() {
       return $this->belongsToMany('App\Item', 'invoice_item', 'invoice_id', 
       'item_id')->withPivot('quantity'); 
}

Item.php

class Item extends Model {
 public function invoices() {
      return $this->belongsToMany('App\Invoice' ,'invoice_item', 'item_id', 'invoice_id');
   }

class Invoice_item extends Model
{
    protected $fillable = [
      'quantity',
    ];
}

listInvoice.blade.php

 @foreach($invoice->items as $item)
<tr>
  <td>{{ $item->pivot->quantity}}</td>
</tr>
  @endforeach 

問題是,當我嘗試顯示數量時,總是出現0 :(我哪里出錯了?

我假設您使用的是Laravel 5.5(因為未提及)

Laerte所述 ,請使用InvoiceItem而不是Invoice_item

並且您的自定義中間模型必須從Pivot擴展; 不是來自Model

<?php namespace App;

use Illuminate\Database\Eloquent\Relations\Pivot;    

class InvoiceItem extends Pivot 
{
    protected $fillable = [
        'quantity',
    ]; 
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM