【问题标题】:How I can remove/add records from a pivot table?如何从数据透视表中删除/添加记录?
【发布时间】:2017-02-20 16:36:37
【问题描述】:

我有以下表格:

  1. 用户
  2. user_friends

users - id、用户名、电子邮件等。

user_friends - 例如user_id、friend_id

我的用户模型中的关系:

public function friends()
    {
        return $this->belongsToMany('App\User', 'user_friends', 'user_id', 'friend_id');
    }

如何为用户添加好友或删除好友?我需要为它创建一个新模型吗?

加好友 -> 将新记录添加到user_friends

删除好友 --> 从user_friends删除特定好友(记录)

【问题讨论】:

    标签: laravel eloquent


    【解决方案1】:

    你应该试试这个:

    $user->friend()->sync(['asd', 'asd1', 'asd2']);
    

    或删除:

    $user->friend()->detach();
    

    或添加新项目:

    $user->friend()->attach(['asd', 'asd1', 'asd2']);
    

    【讨论】:

    • sync 和其他的有什么不同?是否可以在插入新值之前检查该值是否存在?
    • 同步删除所有油炸物品并将你给它的东西附加到数组中。分离只是删除所有或特定项目,附加只是将新项目添加到对象朋友关系。
    • 你可以在这里找到一个很好的文档:laravel.com/docs/5.4/…
    • 谢谢!请您回答第二个问题 - 是否可以在插入新值之前检查该值是否存在?
    • 当然可以:$user->friends()->where('whatyouwanthere')->exists() 这个函数将返回布尔值 true 或 false;
    猜你喜欢
    • 2018-11-14
    • 1970-01-01
    • 2020-11-18
    • 2019-04-25
    • 1970-01-01
    • 2021-06-03
    • 1970-01-01
    • 2013-07-02
    • 1970-01-01
    相关资源
    最近更新 更多