创建具有多个关系的 eloquent 的实例?

Creating instance of eloquent with multiple relationships?

我有 3 个模型: 插件、评论和用户。

用户是插件的父级。在一对多关系中,我可以轻松创建一个与用户关联的插件:

$user->plugins()->create([...options...]);

但现在我的问题是:评论是用户和插件的子项。如何在不手动设置一个 ID 的情况下使用用户和插件创建评论?

假设一个Review属于一个User和一个Plugin,您可以使用关系的associate()方法来设置外键。请注意,此方法仅在对象上设置适当的属性;您仍然需要 save() 更新数据库的对象。

这是一个例子:

$plugin = $user->plugins()->create([...plugin options...]);

// instantiate a new review instance
$review = new \App\Review([...review options...]);

// set the user association
$review->user()->associate($user);

// set the plugin association
$review->plugin()->associate($plugin);

// save the entire record to the database
$review->save();