php 如何使用 eloquent/fluent 从单个查询中插入多行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29723865/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 00:32:22  来源:igfitidea点击:

How to insert multiple rows from a single query using eloquent/fluent

phpsqllaraveleloquent

提问by Billy

I have the following query:

我有以下查询:

  $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 tableso that my table looks like this?

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

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

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

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

回答by Kreshnik Hasanaj

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

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

You can use the following approach.

您可以使用以下方法。

$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

In your case you already have the data within the $queryvariable.

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

回答by Vishal Varshney

using Eloquent

使用雄辩

$data = array(
    array('user_id'=>'Coder 1', 'subject_id'=> 4096),
    array('user_id'=>'Coder 2', 'subject_id'=> 2048),
    //...
);

Model::insert($data);