【问题标题】:How do I access extra fields in a Laravel 5 pivot table?如何访问 Laravel 5 数据透视表中的额外字段?
【发布时间】: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


    【解决方案1】:

    您访问枢轴属性上的属性:

    $item->pivot->quantity
    

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

    dd($item->toArray());
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-06
      • 2018-01-18
      • 1970-01-01
      • 1970-01-01
      • 2017-03-09
      • 2018-08-18
      • 2015-09-21
      • 2019-08-20
      相关资源
      最近更新 更多