drqvsx1228 2017-07-31 12:57 采纳率: 0%
浏览 24
已采纳

数据库继承Laravel 5.4

I am looking forward to implement a website dealing with teachers, students and parents. In the database I made, I've created a user table and 3 children tables : teachers, students, parents. See below the table structure

User table
+--------+----------+----------+-------+
| id (PK)| username | password | email |
+--------+----------+----------+-------+
| 1      | user1    | 123      | ...   |
+--------+----------+----------+-------+
| 2      | user2    | 132      | ...   |
+--------+----------+----------+-------+
| 3      | user3    | 321      | ...   |
+--------+----------+----------+-------+

Student table
+---------------+--------------+
| users_id (PK) | class        |
+---------------+--------------+
| 1             | highschool   |
+---------------+--------------+
| 3             | middleschool |
+---------------+--------------+
Teacher table
+--------------+-------------------+---------------------+
| users_id (PK)| subscription_type | end_of_subscription |
+--------------+-------------------+---------------------+
| 2            | monthly           | 2017-10-25          |
+--------------+-------------------+---------------------+

And the parents table also have a PK which corresponds to a user id. I just started to learn laravel and I really wonder how could I handle this properly maybe with eloquent with Laravel 5.4.

  • 写回答

1条回答 默认 最新

  • dongyi1748 2017-08-01 09:34
    关注

    I am giving you some hints I think you can do rest and as your question is not specific I am guessing you are thinking how can you relate/join tables, so

    1. Create three model let say User, Student, Teacher.
    2. In Student & Teacher model create a method like below
    public function user()
    {
      return $this->hasOne(User::class, 'id', 'users_id');
    }
    

    Now you can query like :

    $student = Student::find($id) ;
    $name = $student->user->name;
    $email = $student->user->email ;
    Or 
    $teachers = Teacher::where('subscription_type', 'monthly')->with(['user'])->get();
    dd($teachers);
    

    I think you need to update your database structure, you need pk & fk column separated.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题