我有两个由透视表和belongsToMany关系连接的Laravel 5模型。如下所示,我有订单,商品和数据透视表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
我似乎无法访问额外字段'数量'。如果我
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'] }}
没有任何输出。
答案 0 :(得分:5)
您可以访问pivot属性上的属性:
$item->pivot->quantity
P.S。将来,不是直接dd
模型,而是首先将其转换为数组:
dd($item->toArray());
只看到属性和关系会更容易。