如何使用 eloquent/fluent 从单个查询中插入多行 [英] How to insert multiple rows from a single query using eloquent/fluent

查看:36
本文介绍了如何使用 eloquent/fluent 从单个查询中插入多行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下查询:

  $query = UserSubject::where('user_id', Auth::id())->select('subject_id')->get();

正如预期的那样,我得到以下结果:

and as expected I get the following result:

[{"user_id":8,"subject_id":9},{"user_id":8,"subject_id":2}]

有没有办法将上述结果复制到另一个表中,使我的表看起来像这样?

Is there a way of copying the above result into another table so that my table looks like this?

ID|user_id|subject_id
1 |8      |9
2 |8      |2

我遇到的问题是 $query 可以预期任意数量的行,因此我不确定如何遍历未知数量的行.

The problem I have is that the $query can expect any number of rows and so im unsure how to iterate through an unknown number of rows.

推荐答案

使用 Eloquent 或查询构建器在 Laravel 中进行批量插入真的很容易.

It is really easy to do a bulk insert in Laravel using Eloquent or the query builder.

您可以使用以下方法.

$data = [
    ['user_id'=>'Coder 1', 'subject_id'=> 4096],
    ['user_id'=>'Coder 2', 'subject_id'=> 2048],
    //...
];

Model::insert($data); // Eloquent approach
DB::table('table')->insert($data); // Query Builder approach

在您的情况下,您已经拥有 $query 变量中的数据.

In your case you already have the data within the $query variable.

这篇关于如何使用 eloquent/fluent 从单个查询中插入多行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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