简体   繁体   English

如何在Laravel中访问Pivot?

[英]How to access Pivot in Laravel?

I'm having problems accessing the Pivot relationship. 我在访问数据透视关系时遇到问题。

 #relations: array:1 [
        "orders_material" => Collection {#250
          #items: []
        }
      ]

I want to get the orders_material that have pivot values null 我想获取具有枢轴值null的orders_material

This is the query : 这是查询:

 $material = Material::with(['orders_material' => function($query)  use ($begin_date, $end_date, $begin_hour, $hour_final) 
     {
        $query->whereBetween('Orders_has_Material.date_begin',[$begin_date, $end_date])
        ->whereBetween('Orders_has_Material.date_final',[$begin_date, $end_date])
        ->where('Orders_has_Material.Material_id', null)
        ->where('Orders_has_Material.Orders_id', null);
      }])

    ->get();

    dd($material);

public function orders_material()
     {
         return $this->belongsToMany('App\Orders', 'Orders_has_Material', 'Material_id', 'Orders_id');
     }

First of all, as I see here u have many columns in ur pivot table like date_begin and date_final so here u need to edit ur relationship models like this : 首先,正如我在这里看到的那样, date_begin在数据透视表中有很多列,例如date_begindate_final因此在这里您需要像这样编辑ur关系模型:

public function orders_material()
 {
     return $this->belongsToMany('App\Orders', 'Orders_has_Material', 'Material_id', 'Orders_id')->withPivot('date_begin', 'date_final', 'column3');
 }

and to access to them just u need to get $material of orders or the inverse. 而要访问它们,您只需要获得$materialorders或倒数即可。

which means, as u get the $material in ur query, i think to want to access to the orders related to that $material and show up some information inside ur pivot table. 这意味着,当您在查询中获得$material时,我认为我想访问与该$material相关的订单,并在您的数据透视表中显示一些信息。 u can access to them like this (if ur relationship models are correct of course): 您可以像这样访问他们(如果您的关系模型正确的话):

foreach($material->orders as $order)
{
   echo $order->pivot->date_begin; 
   echo $order->pivot->date_final; 
}

for more information read the doc many to many laravel with pivot table 有关更多信息,请阅读带有枢轴表的多对多Laravel文档

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

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