Laravel模型创建覆盖 [英] Laravel Model creation override
问题描述
在我的Laravel项目中,我有不同的用户类型,都具有基本的User模型.这是数据库拓扑的简要说明:
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
在我的情况下,每个 Student
, Teacher
, Employee
都有自己的 User
.但是,例如,如果我想创建一个新的 Student
,则必须同时创建一个 Student
和 User
模型.我知道Laravel中的Observers模式可以简化此工作,但我希望能够以编程方式制作 Student
模型,如下所示:
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']);
问题从那里变得更加复杂,因为 Teacher
模型还需要同时具有 Employee
模型和 User
模型.有没有一种方法可以覆盖模型上的 create
方法,以便我可以传递 User
创建参数,还可以传递 Student
参数?>
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?
推荐答案
您可以覆盖 create
方法,然后自己执行.在您的 Student
模型类中,添加以下内容:
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.
如果您的Laravel版本高于5.4.*,请执行以下操作:
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;
}
这篇关于Laravel模型创建覆盖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!