laravel Eloquent ORM 多表插入 [英] laravel Eloquent ORM multiple table insert

查看:41
本文介绍了laravel Eloquent ORM 多表插入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将如何使用 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
  • 图像名称

关系

  1. users id 引用了另外两个表中的 user_id
  2. postsusers 有一对多的关系.
  3. imagesuserspost 有一对多的关系,即它可以与其他用户和其他帖子共享.莉>
  1. Table users id references user_id in other two tables .
  2. Table posts has One To Many relation with users.
  3. Table images has One To Many relation with users and post 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆