druybew06513 2015-07-15 01:30
浏览 41
已采纳

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

I'm building a friendship system in Laravel 5 that requires a user to accept a potential friendship with another user.

I've created a many-to-many relationship between users and "helpers" (other users). The relationships look like this:

// 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);
}

The only difference between them is an additional value in my "helpers" pivot table: "accepted." "Accepted" is a boolean that defaults to 0.

I create the table row when a user first proposes friendship, and then would like to update the row when the friendship is accepted. Here is a version of my controller that condenses the two actions into a single code block:

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();
}

However, I'm getting an error on this line—$accepted->pivot->accepted = 1;—that reads: Creating default object from empty value.

In this case, how would I access and update a value in a pivot table record that I just created?

  • 写回答

1条回答 默认 最新

  • duanjiao3686 2015-07-15 05:19
    关注

    This line: $accepted = $currentUser->potentialFriendsOfMine()->where('helper_id', $input); returns a Builder object. I think you have forgotten to add ->get() at the end to get a model object. In other words:

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

    OR

    $accepted = $currentUser->potentialFriendsOfMine()->where('helper_id', $input)->first();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 使用C#,asp.net读取Excel文件并保存到Oracle数据库
  • ¥15 C# datagridview 单元格显示进度及值
  • ¥15 thinkphp6配合social login单点登录问题
  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配