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.

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

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!