Laravel很多人需要从连接表中获取列

时间:2018-03-10 11:54:02

标签: laravel eloquent many-to-many

我的两张表以这种方式有关系

public function orders() { 
    return $this->belongsToMany('App\Order'); 
}

public function products() { 
    return $this->belongsToMany('App\Product', 'OrderDetails');
}

我如何获得数量的列?在order_product表上定义

1 个答案:

答案 0 :(得分:0)

使用withPivot()

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

$orders = Product::find($id)->orders;
foreach($orders as $order) {
    // $order->pivot->quantity
}