【发布时间】:2015-05-29 23:28:37
【问题描述】:
我有两个通过数据透视表连接的 Laravel 5 模型和 belongsToMany 关系。正如您在下面看到的,我有订单、商品和数据透视表 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'] }}
没有任何输出。
【问题讨论】:
标签: laravel model pivot-table laravel-5