[英]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.