我想将许多行复制到另一个表
表临时数据
| id | name | email | id_transaction | order_number |
|----|------|------------|----------------|--------------|
| 1 | Gery | a@mail.com | A1 | 1 |
| 2 | Ray | b@mail.com | A1 | 2 |
我要将这些行复制到表 MAIN DATA
| id | name | email | id_transaction | order_number |
我要检查id_transaction
和order_number
是否存在,该行将不会复制到MAIN DATA。
这是我到目前为止已经尝试过的方法,但是它只是从id _transaction
复制第一行
| 1 | Gery | a@mail.com | A1 | 1 |
$copy = TEMPORARYDATA::where('id_transaction', '=', $id_trans )->get()->toArray();
foreach ($copy as $copy)
{
$count = MAINDATA::where('id_transaction', $id_trans)->groupby('order_num')->count('order_num');
if ($count > 0)
{}
else
{
$save_copy = array_except($copy, ['created_at', 'updated_at','id']);
MAINDATA::insert($save_copy);
}
}
答案 0 :(得分:0)
尝试删除您要复制的记录id
(如果您不在乎)或进行更改。我还建议您返回$copy
的值,以了解该变量的填充方式,如果未按预期填充该变量,请使用toSql()
输出要查询的查询执行。
无论如何,您应该计算MAINDATA
条记录,外部 for
循环,因为您多次重复同一查询,这是无用的,而且浪费了资源您的机器。
您提供的代码应为:
$copy = TEMPORARYDATA::select('name', 'email', 'id_transaction', 'order_number')
->where('id_transaction', '=', $id_trans )
->get()
->toArray();
$count = MAINDATA::where('id_transaction', $id_trans)
->groupby('order_num')
->count();
foreach ($c as $copy)
{
if ($count > 0)
;
else
MAINDATA::insert($c);
}
N.B。::确保要在表中插入的属性位于模型的protected $fillable
数组中。进一步了解here
答案 1 :(得分:0)
尝试使用此代码将TEMPORARY DATA表传输到MAIN DATA表,您的条件也得到满足。 $ temporary_Data = [];
`$ temporary_Data = TEMPORARYDATA :: where('id_transaction','=',$ id_trans)-> get()
foreach($ temporary_Data作为$ data)
{
$mainObj =['name' => $temporary_Data->name,
'email' => $temporary_Data->email,
'id_transaction'=> $temporary_Data->id_transaction,
'order_number'=> $temporary_Data->order_number,]
MAINDATA :: create($ data);
}`