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

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

问题描述

表1:用户


$我如何使用laravel Eloquent ORM关系将多个表格中的单个请求插入多个表格中。



b $ b


  • id

  • 名称

  • 电子邮件



表2:帖子




  • id

  • user_id

  • 内容



表3:图片




  • id

  • user_id

  • post_id

  • image_name



关系


  1. 用户 id引用 user_id 在其他两个表中。

  2. 帖子用户有一对多关系

  3. 图像用户 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
  • email

Table 2 : posts

  • id
  • user_id
  • content

Table 3 : Image

  • id
  • user_id
  • post_id
  • image_name

relationship

  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.

解决方案

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屋!

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