我一直在尝试从与laravel的关系中更新pivot信息。我尝试了两种不同的方法:1($message->notifications->users->first((->pivot->read=1;$message->save((;
2(
$message->notifications->users->first()->updateExistingPivot($user, ['read' => 1]);
第一个不起作用,没有错误,只是不更新。第二个抛出错误:
Call to undefined method AppUser::updateExistingPivot();
在我的模型中,我的关系是这样的:
用户.php
public function notifications()
{
return $this->belongsToMany('AppNotification','users_notifications')->withPivot('read')->wherePivot('read',0);
}
通知.php
public function users()
{
return $this->belongsToMany('AppUser', 'users_notifications')->withPivot('read');
}
消息.php
public function notifications()
{
return $this->belongsTo('AppNotification','id');
}
我被困在这里了,请帮帮我!
如果需要更新数据透视表中的现有行,可以使用updateExistingPivot方法。此方法接受数据透视记录外键和属性数组以更新
因此,如果您想更新一个用户的所有通知。此处不能使用updateExistingPivot
。
但是,您可以尝试在notifications()
关系中使用newPivotStatement
,newPivotStatement
会找到透视表中的所有记录,因此您需要使用where
来筛选您想要的记录。
$user->notifications()
->newPivotStatement()
->where('user_id', $user->id)
->update(['read' => 1]);
或者查询生成器的有效方法:
DB::table('users_notifications')
->where('user_id', $user_id)
->update(['read' => 1]);