【问题标题】:Laravel - Many To ManyLaravel - 多对多
【发布时间】:2016-09-03 05:15:37
【问题描述】:

我有两个具有多对多关系的主表和一个数据透视表。

Tables

模型产品

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

模型顺序

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

$orders = Equipment::all();

@foreach($orders as $order)
    @foreach($order->products as $product)
        {!! $product->name !!} //it works
        // How to print the value of the quantity?
    @endforeach
@endforeach

如何打印数量的值?

【问题讨论】:

  • 您可以使用几种不同的方法。我通常更喜欢将此表命名为 order_items,并且在 order 表中使用 hasMany 到 oder_items 和 d HasManyThrough 与产品表的关系。在您的情况下,数据透视表,您可以使用 withPivot 函数。本文提供了对pivot table 的深入了解

标签: php database laravel many-to-many relationship


【解决方案1】:

试试->pivot->quantity

{!! $product->pivot->quantity !!}

另外,将withPivot 添加到关系中:

return $this->belongsToMany('App\Product', 'OrderDetails')->withPivot('quantity');

https://laravel.com/docs/5.2/eloquent-relationships#many-to-many

【讨论】:

  • 如何将多个 id 保存到模型中?像这样$user->roles()->sync([1 => ['expires' => true], 2, 3]);
猜你喜欢
  • 1970-01-01
  • 2022-06-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-30
  • 2017-09-30
  • 2016-08-27
相关资源
最近更新 更多