簡體   English   中英

Laravel 附加了 manytomany 和額外的字段

[英]Laravel attach manytomany with extra field

有3張桌子。 產品、用戶和 product_user。 product_user 表中有 3 個字段。 product_id、user_id 和價格。

product_id 和 user_id 將被自動附加和填充。 但我想要一個名為 price 的文本字段,用戶填寫它以插入到數據庫的 price 字段中。

我的意思是我想在附加時插入一個文本字段。

首先要在數據透視表中插入一個額外的字段,您需要在模型中指定這個額外的字段。

例如這個:

在產品型號中

public function users()
{
   return $this->belongsToMany('App\User', 'product_user')
                    ->withPivot('price');
}

在用戶模型中

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

此外,在您的控制器中,您可以像這樣附加這個額外的字段:

$product->users()->attach($user_id, ['price'=> $price ]);

我希望這能幫到您 !!!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM