[英]How to update data of pivot table in Many To Many relationship
I have a Many To Many relationshp between User Model & Wallet Model.我在用户模型和钱包模型之间有一个多对多的关系。
So at the User.php Model:所以在 User.php 模型中:
public function wallets()
{
return $this->belongsToMany(Wallet::class,'user_wallet','user_id','wallet_id')->withPivot('balance');
}
And at Wallet.php Model:在 Wallet.php 模型中:
public function users()
{
return $this->belongsToMany(User::class,'user_wallet','wallet_id','user_id');
}
And also the table Migration of user_wallet
table also goes here:而且
user_wallet
表的表迁移也放在这里:
public function up()
{
Schema::create('user_wallet', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('user_id');
$table->foreign('user_id')->references('usr_id')->on('users');
$table->unsignedBigInteger('wallet_id');
$table->foreign('wallet_id')->references('id')->on('wallets');
$table->integer('balance');
$table->timestamps();
});
}
And at the Controller, I added this:在控制器中,我添加了以下内容:
$bal = Wallet::with("users")->whereHas('users',function ($query)use($wallet_id,$user_id){
$query->where('wallet_id',$wallet_id);
$query->where('user_id',$user_id);
});
dd($bal);
But now I need to update balance
filed of this pivot table which has the same user_id
and wallet_id
:但是现在我需要更新这个具有相同
user_id
和wallet_id
数据透视表的balance
文件:
So how to do this?那么如何做到这一点呢?
I would really appreciate any idea or suggestion from you guys...我真的很感激你们的任何想法或建议......
Thanks in advance.提前致谢。
use updateExistingPivot
使用
updateExistingPivot
$wallet = Wallet::find($wallet_id);
$wallet->users()->updateExistingPivot($user_id,["balance"=>500]);
Ref: https://laravel.com/docs/8.x/eloquent-relationships#updating-a-record-on-the-intermediate-table参考: https : //laravel.com/docs/8.x/eloquent-relationships#updating-a-record-on-the-intermediate-table
use something like this:使用这样的东西:
$bal->users()->sync([
$user_id => [
'balance' => 1
],
]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.