Laravel Model creation override

可紊 提交于 2021-01-29 13:48:22

问题


In my Laravel project, I have different user types that all have a base User model. Here's a brief idea of the database topology:

users:
 - id
 - name
 - email

students:
 - age
 - user_id

teachers:
 - budget
 - user_id

employee:
 - is_admin
 - user_id

In my case, each of Student, Teacher, Employee has their own User. But if I want to make a new Student for example, I have to make both a Student and User model. I'm aware of the Observers pattern in Laravel which can make this job easier, but I'd like to be able to programatically make Student models like the following:

$student = App\Student::create(['name' => 'Joe', 'email' => 'joe@example.net', 'age' => '20']);

The problem gets even more complex from there, because Teacher models are also required to have both an Employee model and a User model. Is there a way to override the create method on my model so that I can pass in User creation parameters, but also Student parameters?


回答1:


You can override the create method and do this yourself. In your Student model class add this:

public static function create($arr) {
    $user = User::create([
        'name' => $arr['name'],
        'email' => $arr['email']
    ]);

    $student = parent::create([
        'age' => $arr['age']
        'user_id' => $user->id
    ]);

    return $student;
}

You can do other methods in a similar way.

If you Laravel version is above 5.4.* do this instead:

public static function create($arr) {
    $user = User::create([
        'name' => $arr['name'],
        'email' => $arr['email']
    ]);

    $student = static::query()->create([
         'age' => $arr['age']
         'user_id' => $user->id
    ]);

    return $student;
}


来源:https://stackoverflow.com/questions/61070392/laravel-model-creation-override

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!