Eloquent 多对多关系访问 table 来自数据透视表的列值 table

Eloquent many to many relationship access table column value from pivot table

我有两个模型:

class Order extends Eloquent 
{
    public function User()
    {
        return $this->belongsTo('User');
    }

    public function Product()
    {
        return $this->belongsToMany('Product');
    }
}

第二个是:

class Product extends Eloquent 
{
    public function Order()
    {
        return $this->belongsToMany('Order');
    }
}

我的问题是如何使用 pivot table:

访问第二个 table 列的值

产品table:

id
title
image

订单table:

id
status

枢轴 table(order_product):

id
product_id
order_id

我需要访问订单中产品的标题栏。例如,如果用户在一个订单中订购了很多产品,我可以获取所有产品标题并显示主题。 我不喜欢使用 join ,而是喜欢使用 Laravel 功能本身。

我找到了答案:

$orders = Order::orderBy('created_at', 'DESC')->paginate($page_number);

foreach($orders as $item){
  foreach($item->product as $item){
     {{$item->title}}<br>
  }
}

我可以访问订单中的产品。