我的数据透视表中有4个额外的属性('product_id','quantity','discount_percent','discount_amount'),但是当我存储时,我的值总是0,而其余属性正确填充。有什么想法吗?
发票模型
public function productversion()
{
return $this->belongsToMany('App\Productversion')->withPivot('product_id', 'quantity', 'discount_percent', 'discount_amount')->withTimestamps();
}
Productversion模型
public function invoice()
{
return $this->belongsToMany('App\Invoice')->withPivot('product_id', 'quantity', 'discount_percent', 'discount_amount')->withTimestamps();
}
控制器(商店)
$invoice->productversion()->attach($productversionid, ['product_id' => $productid], ['quantity' => $qty], ['discount_percent' => $discountprc], ['discount_amount' => $discountamt]);
答案 0 :(得分:6)
只需要一个阵列:
$invoice->productversion()->attach($productversionid, [
'product_id' => $productid,
'quantity' => $qty,
'discount_percent' => $discountprc,
'discount_amount' => $discountamt
]);
答案 1 :(得分:2)
除了@ jeff的方法之外,您还可以使用pivot属性附加或同步多个元素,从而提供具有id作为键的多维数组。
$attach_data[$productversionid] = [
'product_id' => $productid,
'quantity' => $qty,
'discount_percent' => $discountprc,
'discount_amount' => $discountamt
];
然后你可以$invoice->productversion()->attach($attach_data)
。
基本上你可以传递像
这样的数组[
'relation_id' => [
// pivot data
],
'relation_id' => [
// pivot data
],
// ...
]