为了账号安全,请及时绑定邮箱和手机立即绑定

如何在没有枢轴模型的情况下在 Laravel 中存储多对多关系?

如何在没有枢轴模型的情况下在 Laravel 中存储多对多关系?

PHP
湖上湖 2024-01-19 20:50:27
我正在尝试创建多对多关系我有 2 个主表和 1 个数据透视表userid : 1name : lily eventid: 1event_name: Waterpark Waterday-------id: 2event_name :Theme Park Adventureevent_userid : 1event_id : 2user_id : 1-------------id :2event_id :1user_id :1表用户和事件都已创建。仅当用户想要加入事件时创建数据透视表或关系。因此,当用户单击“应用”按钮时,它只会存储event_id并且user_id我想创建类似的东西。但我有问题,我不太确定如何保存它。它确实尝试过,但我不断收到错误。
查看完整描述

2 回答

?
千巷猫影

TA贡献1829条经验 获得超7个赞

你可以使用attachdetach方法。

您还可以使用该sync方法来构造多对多关联。该sync方法接受要放置在中间表上的 ID 数组。任何不在给定数组中的 ID 都将从中间表中删除。因此,此操作完成后,中间表中将只存在给定数组中的 ID:

$user->events()->sync([1,2]);

数组中1,2是事件 id。

笔记

因为sync, attach您应该在模型中定义关系。

用户模型

class User extends Model

{

    public function events()

    {

        return $this->belongsToMany('App\Event','event_user','user_id','event_id');

    }

}

事件模型


class Event extends Model

{

    public function users()

    {

        return $this->belongsToMany('App\User','event_user','event_id','user_id');

    }

}

根据您的代码。


$user = User::find(Auth::user()->id);

$user->events()->sync([$request->event_id]);


查看完整回答
反对 回复 2024-01-19
?
翻翻过去那场雪

TA贡献2065条经验 获得超13个赞

我的可选答案:


(因为当您有大数据时,附加比同步更快)


//get current synced id

$attachedIds = $user->events()->pluck('id');

//check if there is a new id selected

//if its a single id

$new_id = array_diff([$request->event_id], $attachedIds);

//if its already an array

$new_id = array_diff($request->input('event_id', []), $attachedIds);


$user->events()->attach($new_id);


查看完整回答
反对 回复 2024-01-19
  • 2 回答
  • 0 关注
  • 52 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信