laravel Eloquent ORM 多表插入 [英] laravel Eloquent ORM multiple table insert
问题描述
我将如何使用 laravel Eloquent ORM 关系在多个表中插入单个请求.即
How would i make a single request to insert in multiple tables using laravel Eloquent ORM relationship .ie
表一:用户
- id
- 姓名
- 电子邮件
表 2:帖子
- id
- user_id
- 内容
表 3:图片
- id
- user_id
- post_id
- 图像名称
关系
- 表
users
id 引用了另外两个表中的user_id
- 表
posts
与users
有一对多的关系. - 表
images
与users
和post
有一对多的关系,即它可以与其他用户和其他帖子共享.莉>
- Table
users
id referencesuser_id
in other two tables . - Table
posts
has One To Many relation withusers
. - Table
images
has One To Many relation withusers
andpost
ie it can be shared with other users and on other posts.
这样,当进行后插入时,它应该使用单个查询将记录插入表中.
So that when one makes a post insert ,it should insert the record in the tables with a single query.
推荐答案
这是一种方法:
$post = (new Post)->fill($request->all()->toArray())->user()->associate(Auth::user())->save();
对于图片来说,Post
模型应该有一个模型事件,比如static::created
来处理图片的上传和操作.
As for the image, the Post
model should have a model event such as static::created
to handle the image upload and manipulation.
或者更有意义的是,Post
模型中的模型事件应该触发 Image
模型中的另一个模型事件.
Or to make more sense, a model event in the Post
model should trigger another model event from the Image
model.
->toArray()
可能是可选的,我无法在这里测试它.
->toArray()
may be optional, I can't test it here where I'm now.
这篇关于laravel Eloquent ORM 多表插入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!