Laravel将数据复制到其他表,检查是否存在

I want to copy many row to another table

table TEMPORARY DATA

| id | name |  email     | id_transaction | order_number |
|----|------|------------|----------------|--------------|
| 1  | Gery | a@mail.com | A1             | 1            |
| 2  | Ray  | b@mail.com | A1             | 2            |

I want to copy these rows to table MAIN DATA

| id | name | email | id_transaction | order_number |

I want to check if id_transaction and order_number exists, the row will not copy to MAIN DATA.

This is what i've tried so far, but it's only copying the first row from 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);
    }
}

Try to remove id of the record you wish to copy (if you don't care it) or change it. I also suggest you to return the value of $copy to have an idea of how that variable is filled, and, if it isn't filled as you expected, use toSql() to output the query you're executing.

Anyway, you should count MAINDATA records, outside for loop, 'cause you're repeating the same query many times, that's useless and a waste of resources of your machine.

The code you provided should be:

$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.: make sure properties you're trying to insert in table are in protected $fillable array in your model. Read more about it here

Try to this code for transfer TEMPORARY DATA table to MAIN DATA table and your condition also satisfied. $temporary_Data = [];

`$temporary_Data = TEMPORARYDATA::where('id_transaction', '=', $id_trans )->get()

foreach($temporary_Data as $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); }`