[英]Laravel attach manytomany with extra field
There are 3 tables.有3张桌子。 Products, Users and product_user.
产品、用户和 product_user。 There are 3 fields in product_user table.
product_user 表中有 3 个字段。 product_id, user_id and price.
product_id、user_id 和价格。
product_id and user_id will be attached and filled automatically. product_id 和 user_id 将被自动附加和填充。 But I want a textfield named price which user fill it to be inserted in price field in database.
但我想要一个名为 price 的文本字段,用户填写它以插入到数据库的 price 字段中。
I mean I want to insert a textfield when attaching.我的意思是我想在附加时插入一个文本字段。
To insert an extra field in your pivot table first of all, you need to specify this extra field in your models.首先要在数据透视表中插入一个额外的字段,您需要在模型中指定这个额外的字段。
For Example this:例如这个:
In Product model在产品型号中
public function users()
{
return $this->belongsToMany('App\User', 'product_user')
->withPivot('price');
}
In User model在用户模型中
public function products()
{
return $this->belongsToMany('App\Product', 'product_user')
->withPivot('price');
}
Furthermore, in you Controller you can attach this extra field like this:此外,在您的控制器中,您可以像这样附加这个额外的字段:
$product->users()->attach($user_id, ['price'=> $price ]);
I hope this will help you !!!我希望这能帮到您 !!!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.