如何将另一个表数据插入另一个表laravel 5.2?
我有两个表:如何将另一个表数据插入另一个表laravel 5.2?
qr_details表:
id product_id qrcode_id created_at updated_at
1 1 12 2017-10-09 15:36:15 2017-10-09 15:36:15
2 3 13 2017-10-09 15:36:15 2017-10-09 15:36:15
赢家表:
id product_id qrcode_id winner_name win_number created_at updated_at
1 1 12 hello 5 2017-10-09 15:36:15 2017-10-09 15:36:15
2 3 13 world 6 2017-10-09 15:36:15 2017-10-09 15:36:15
现在我想qr_details
表product_id
& qrcode_id
到winners
表。我如何在Laravel中查询?我做了一个SQL小提琴here。提前致谢。
我真的不明白你的问题,但你可以试试这个:
$datas = DB::table('qr_details ')->get();
foreach($datas as $data){
DB::table('winners')->insert(['qrcode_id' => $data->qrcode_id, 'product_id'=>$data->product_id, ...bunch other inserts])
}
如果有人插入数据赢家表,那么我想要'qr_details'表'product_id'&'qrcode_id'到'winners'表中。你的答案通过错误'Undefined property:stdClass :: $ product_id' –
如果你是新的记录添加到winners
表,那么你可以使用Eloquent
模型和insert
方法来添加多个纪录一个查询。
$qcodes = Qrcode::all()->map(function(Qrcode $qrcode) {
return [
'id' => $qrcode->id,
'product_id' => $qrcode->product_id,
'qrcode_id' => $qrcode->qrcode_id,
'winner_name' => 'some name',
'win_number' => 5
];
});
Winner::insert($qcodes);
然而,从你说的猜测,这可能不是你以后在做什么 - 只要你想只product_id
和qrcode_id
添加 - 换句话说,以更新现有记录。
如果是这样的话,如果你的id
列在两个表的匹配,那么你可以做类似的东西:
$qcodes = Qrcode::all();
$qcodes->each(function(Qrcode $qrcode) {
Winner::where('id', $qrcode->id)->update([
'product_id' => $qrcode->product_id,
'qrcode_id' => $qrcode->qrcode_id
]);
});
这又假设你使用Eloquent
模型 - 否则,你就会有要做到这一点使用Query Builder
:
$qcodes= DB::table('qr_details')->get();
$qcodes->each(function(Qrcode $qrcode) {
DB::table('winners')
->where('id', $qrcode->id)
->update([
'product_id' => $qrcode->product_id,
'qrcode_id' => $qrcode->qrcode_id
]);
});
请确保您相应地更新表/型号名称。
现在,有一个问题与你的SQL结构是您winners
表product_id
和qrcode_id
是NOT NULL
所以它必须有一些数据出现在第一次创建记录时。如果您要更新这些记录,我建议将这两列更改为NULL
,以便最初他们不需要任何数据。
只需使用简单的获取查询获取'qr_details'表的详细信息,然后使用它插入! –