简体   繁体   English

从数据透视表中剔除多对多关系访问表列值

[英]Eloquent many to many relationship access table column value from pivot table

I have two models: 我有两个型号:

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

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

and the second one is: 第二个是:

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

My question is how can i access a value of second table column using pivot table: 我的问题是如何使用数据透视表访问第二个表列的值:

product table: 产品表:

id
title
image

order table: 订单表:

id
status

pivot table(order_product): 数据透视表(order_product):

id
product_id
order_id

I need to access title column of products from orders. 我需要从订单访问产品的标题栏。 for example if a user orders many products in one order I can fetch all product title and show theme. 例如,如果用户在一个订单中订购了许多产品,我可以获取所有产品标题并显示主题。 I don't like use join , instead I like to use Laravel functionality itself. 我不喜欢使用join,而是喜欢使用Laravel功能本身。

I found the answer: 我找到了答案:

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

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

I can access products from order. 我可以从订单访问产品。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM