繁体   English   中英

更新Laravel 5中的其他数据透视表值

[英]Update additional pivot table value in Laravel 5

我正在Laravel 5中构建一个友谊系统,该系统要求用户接受与另一个用户的潜在友谊。

我已经在用户和“帮助者”(其他用户)之间建立了多对多关系。 关系看起来像这样:

// Accepted Friendships
function friendsOfMine()
{
  return $this->belongsToMany('App\User', 'helpers', 'user_id', 'helper_id')
    ->wherePivot('accepted', '=', 1);
}

// Potential Friendships
function potentialFriendsOfMine()
{
  return $this->belongsToMany('App\User', 'helpers', 'user_id', 'helper_id')
    ->wherePivot('accepted', '=', 0);
}

它们之间的唯一区别是我的“帮助器”数据透视表中的附加值:“已接受”。 “已接受”是默认为0的布尔值。

我在用户首先提出友谊时创建表行,然后在接受友谊时更新表行。 这是我的控制器的一个版本,它将两个动作浓缩为一个代码块:

public function store()
{
    $currentUser = Auth::user();
    $input = Input::get('helper_id');
    $helper = User::find($input);

    /* Creates "unaccepted" relationship */
    $currentUser->friendsOfMine()->attach($helper);

    /* Fetches newly created relationship */
    $accepted = $currentUser->potentialFriendsOfMine()->where('helper_id', $input);

    /* Updates "accepted" column and saves */
    $accepted->pivot->accepted = 1;
    $accepted->pivot->save();
    Flash::success('You are now following this user.');
    return Redirect::back();
}

但是,我在这条线上出现了错误- $accepted->pivot->accepted = 1; 的内容为:从空值创建默认对象。

在这种情况下,我将如何访问和更新刚创建的数据透视表记录中的值?

这行代码: $accepted = $currentUser->potentialFriendsOfMine()->where('helper_id', $input); 返回一个Builder对象。 我认为您忘了最后添加->get()来获取model对象。 换一种说法:

$accepted = $currentUser->potentialFriendsOfMine()->where('helper_id', $input)->get();

要么

$accepted = $currentUser->potentialFriendsOfMine()->where('helper_id', $input)->first();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM