doumen6532 2018-04-09 02:30
浏览 165
已采纳

如何访问Laravel中的Pivot?

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

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');
     }
  • 写回答

1条回答 默认 最新

  • dqroc48068 2018-04-09 02:58
    关注

    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 :

    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.

    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. 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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部