且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Laravel模型创建覆盖

更新时间:2023-02-19 17:59:04

您可以覆盖 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;
}