如何解决Laravel updateExistingPivot不断返回假
以下是我与多对多关系和数据透视表的内容。因此,我想将user_id更新为1数据透视表,其中trophy_id = 3。但是,它始终返回0或false。
Trophy.php
public function users()
{
return $this->belongsToMany('App\User','trophies_users','trophy_id','user_id');
}
User.php
public function trophies()
{
return $this->belongsToMany('App\Trophy','user_id','trophy_id');
}
数据透视表
public function up()
{
Schema::create('trophies_users',function (Blueprint $table) {
$table->id();
$table->integer('trophy_id');
$table->integer('user_id');
$table->timestamps();
});
}
在我的控制器中,我正在尝试更新数据透视表
UserController @ index
public function index(Request $request)
{
$user = User::find(1);
$trophyId = 3;
$attributes = ['user_id' => 1];
$res = $user->trophies()->updateExistingPivot($trophyId,$attributes);
dd($res); //Keeps returning 0 or false
}
解决方法
您正在将属性传递给updateExistingPivot
,该属性用于更新数据透视表上的额外属性。
例如,假设我们要为每个用户和奖杯存储一种颜色,我们可以通过在数据透视表中添加一个额外的列并在其上保存颜色数据来实现这一目的,如下所示:
|---------------------|
| column |
|---------------------|
| id |
|---------------------|
| user_id |
|---------------------|
| trophy_id |
|---------------------|
| color |
|---------------------|
如果要更新数据透视表上的关系,请使用sync
方法。
$user=User::find(1);
$trophies_id=[1,2,3];
$user->trophies()->sync($trophies_id);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。