Laravel5.3-创建一定数量的相关模型-创建模型时

Laravel5.3 - Create certain number of related models - when a model is created

我有两个模型:

模型 1 的关系:

public function model2()
{
    return $this->hasMany('App\Model2');
}

关系模型 2:

public function model1()
{
    return $this->belongsTo('App\Model1');
}

我需要在创建 Model1 时创建一定数量 (4) 个具有不同类型设置的 Model2(因此,不是随机的 Model2,仅与 Model1 相关)。在创建 Model2 时,能够访问 Model1 的参数非常重要。 有什么elegant/automatic方法吗? 我的第一个想法是为 Model1 创建一个方法,但我怀疑有更优雅的方法。

您可以对第一个模型使用 created 事件。

https://laravel.com/docs/5.3/eloquent#events

Events allow you to easily execute code each time a specific model class is saved or updated in the database.