如何使用雄辩/流利的方式从单个查询中插入多行 [英] How to insert multiple rows from a single query using 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.
您可以使用以下方法。
You can use the following approach.
$data = array(
array('user_id'=>'Coder 1', 'subject_id'=> 4096),
array('user_id'=>'Coder 2', 'subject_id'=> 2048),
//...
);
Model::insert($data); // Eloquent
DB::table('table')->insert($data); // Query Builder
在您的情况下,您已经有$ query变量中的数据。
In your case you already have the data within the $query variable.
这篇关于如何使用雄辩/流利的方式从单个查询中插入多行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文