如何访问 Laravel 5 数据透视表 table 中的额外字段?

How do I access extra fields in a Laravel 5 pivot table?

我有两个 Laravel 5 模型,通过枢轴 table 和 belongsToMany 关系连接。正如您在下面看到的,我有订单、商品和枢轴 table item_order.

订单:

public function items() {
    return $this -> belongsToMany('App\Item', 'item_order', 'order_id', 'item_id') -> withPivot('id','quantity');
}

项目:

public function orders() {
    return $this -> belongsToMany('App\Order', 'item_order', 'item_id', 'order_id') -> withPivot('id','quantity');
}

循环时

$orders->items as $item

我似乎无法访问额外字段 'quantity'。如果我

dd($item) 

我得到:

Item {#310 ▼
  #table: "items"
  +timestamps: true
  #dates: array:1 [▶]
  #connection: null
  #primaryKey: "id"
  #perPage: 15
  +incrementing: true
  #attributes: array:11 [▼
    "id" => 1
    "created_at" => "2015-03-23 21:30:19"
    "updated_at" => "2015-03-25 15:37:23"
    "deleted_at" => null
    "name" => "Medium Lift Sling"
    "description" => "Green with orange details"
    "url" => "http://www.atlaslifttech.com/slings/patienthighback"
    "image" => "atlas-highback-sling.jpg"
    "manufacturer_id" => 1
    "itemtype_id" => 1
    "notes" => null
  ]
  #original: array:15 [▼
    "id" => 1
    "created_at" => "2015-03-23 21:30:19"
    "updated_at" => "2015-03-25 15:37:23"
    "deleted_at" => null
    "name" => "Medium Lift Sling"
    "description" => "Green with orange details"
    "url" => "http://www.atlaslifttech.com/slings/patienthighback"
    "image" => "atlas-highback-sling.jpg"
    "manufacturer_id" => 1
    "itemtype_id" => 1
    "notes" => null
    "pivot_order_id" => 1
    "pivot_item_id" => 1
    "pivot_id" => 6
    "pivot_quantity" => 0
  ]
  #relations: array:2 [▶]
  #hidden: []
  #visible: []
  #appends: []
  #fillable: []
  #guarded: array:1 [▶]
  #casts: []
  #touches: []
  #observables: []
  #with: []
  #morphClass: null
  +exists: true
  #forceDeleting: false
}

所以数量低于原来的数量,但我已经试过了

{{ $item->quanity }} and {{ $item->pivot_quantity }}

甚至

{{ $item->original['pivot_quantity'] }}

而且什么也没有输出。

您访问数据透视表上的属性 属性:

$item->pivot->quantity

P.S. 以后不直接dd模型,先转成数组:

dd($item->toArray());

仅查看属性和关系会更容易。