如何在laravel的一个“user”表中建立父级和子级的关系

ggazkfy8  于 2021-06-17  发布在  Mysql
关注(0)|答案(1)|浏览(306)

我正在制作一个学校管理系统,我被告知只制作一个“用户”表,而不是制作学生、家长和老师的不同表。我很困惑如何才能注册学生与他的父母的关系。我创建这个项目使用拉威尔框架5.7

kxeu7u2r

kxeu7u2r1#

好吧,要将一个类的对象链接到同一个类(a)的父对象,只需在属性中设置它: students 表架构

id
parent_id // <--- this is the key.
name
...

/**

* this addional (and optional) attribute can help you to identify
* if this is the parent of the branch, because with
* this approach you can have grandchilds and so on..
**/

is_root // <---

然后在您的模型中:
用户.php

public function parent()
{
    return $this->belongsTo(User::class, 'parent_id');
}

现在,关于用户类型,您还可以设置一个属性来了解用户类型:

id
parent_id
name
type // <-- this could show the user type: 'student', 'teacher', etc

相关问题