【问题标题】:Laravel, how to insert into pivot tableLaravel,如何插入数据透视表
【发布时间】:2022-01-01 15:26:15
【问题描述】:

我有 3 张桌子:

  • 医生(身份证、姓名)
  • 时间表(id、day)
  • Doctor_schedule(id、doctor_id、shcedule_id、t_start、t_end)

我的问题是如何插入 Doctor_schedule 表? 我有这样的形式: [在此处输入图片描述][1] 这是医生时间表,我想像这样添加医生时间表: [在此处输入图片描述][2]

谢谢你的回答。。 [1]:https://i.stack.imgur.com/8l2Rx.png [2]:https://i.stack.imgur.com/cZMqm.png

【问题讨论】:

    标签: laravel eloquent pivot


    【解决方案1】:

    您必须像这样在 Doctor 模型中定义关系:

    public function schedules()
    {
        return $this->belongsToMany(Schedule::class)->withPivot('t_start', 't_end');
    }
    

    在您的 Schedule 模型中也是如此:

    public function doctors()
    {
        return $this->belongsToMany(Doctor::class)->withPivot('t_start', 't_end');
    }
    

    然后,在您的控制器中,您可以像这样插入记录:

    $doctor->schedules()->attach($scheduleId, ['t_start' => $tStart, 't_end' => $tEnd]);
    

    或者你也可以反其道而行之:

    $schedule->doctors()->attach($doctorId, ['t_start' => $tStart, 't_end' => $tEnd]);
    

    【讨论】:

    • 这是我的代码:
    猜你喜欢
    • 2020-09-19
    • 2018-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-24
    • 1970-01-01
    • 2020-10-21
    • 1970-01-01
    相关资源
    最近更新 更多