laravel雄辩ORM多表插入 [英] laravel Eloquent ORM multiple table insert
问题描述
表1:用户
$我如何使用laravel Eloquent ORM关系将多个表格中的单个请求插入多个表格中。
b $ b
- id
- 名称
- 电子邮件
表2:帖子
- id
- user_id
- 内容
表3:图片
- id
- user_id
- post_id
- image_name
-
关系
- 表
用户
id引用user_id
在其他两个表中。 - 表
帖子
与用户有一对多关系
。 - 表
图像
与用户
和post
有一对多关系,即可以共享与其他用户和其他帖子。
所以当一个人做一个帖子插入时,它应该插入t他在表中记录了一个查询。
这是一种方法:
$ post =(new Post) - > fill($ request-> all() - > toArray()) - > user() - >准(AUTH ::用户()) - >保存();
至于图像, Post
应该有一个模型事件,如 static :: created
来处理图像上传和操作。
或者使更有意义的是, Post
模型中的模型事件应该从 Image
模型中触发另一个模型事件。
- > toArray()
可能是可选的,我现在不能在这里测试。
How would i make a single request to insert in multiple tables using laravel Eloquent ORM relationship .ie
Table 1 : users
- id
- name
Table 2 : posts
- id
- user_id
- content
Table 3 : Image
- id
- user_id
- post_id
- image_name
relationship
- 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.
This is one way of doing it:
$post = (new Post)->fill($request->all()->toArray())->user()->associate(Auth::user())->save();
As for the image, the Post
model should have a model event such as static::created
to handle the image upload and manipulation.
Or to make more sense, a model event in the Post
model should trigger another model event from the Image
model.
->toArray()
may be optional, I can't test it here where I'm now.
这篇关于laravel雄辩ORM多表插入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!