Laravel - 多对多

4
我有两个主表,它们之间是多对多的关系,并且有一个中间表。

表格

模型 产品

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",在订单表中使用hasMany关联到order_items表,并通过product表进行hasManyThrough关联。在您的情况下,可以使用pivot表,您可以使用withPivot函数。这篇文章提供了对pivot表的深入了解。 - Ankit
1个回答

5

你如何将多个ID保存到一个模型中?就像这样$user->roles()->sync([1 => ['expires' => true], 2, 3]); - Ravi Wadhwani

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接