我有 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();
关于php - 创建具有多种关系的 Eloquent 实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34834938/