检查 Laravel 中的重复数据

Checking duplicated data in Laravel

此代码的工作原理是从 ext_db.

发送到 inn_db table

但它无法检查 inn_db 中的数据是否相同或不同。

因此在 inn_db 中设置了相同的值。

我怎样才能添加那份工作?

Laravel-5.4, MySQL, InnoDB.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use \DB;

class UpdateCustomerController extends Controller
{
    public function db_update()
    {
        $customers = \DB::connection('ext_db')->table('customers')->orderBy('customer_id')->chunk(1000, function ($all){
            foreach ($all as $kunde){
                DB::connection('inn_db')->table('custoemrs')->insert(
                    [$kunde->customer_id
                     $kunde->name,
                     $kunde->email]);
            }
        });
    }
}

最后,经过讨论,我得到了以下带有连接视图的代码的答案。

感谢@Pramid 和@Badea :)

    $customers = \DB::connection('ext_db')->table('customers')->orderBy('customer_id')->chunk(1000, function ($all){
        foreach ($all as $kunde){
            $existing_kunde = DB::connection('inn_db')->table('customers')->where([
                    ['customer_id', '=', $kunde->customer_id], 
                    ['name', '=',  $kunde->name], 
                    ['email', '=', $kunde->email]
            ])->first();

            if ( ! $existing_kunde) {
                DB::connection('inn_db')->table('customers')->insert([
                    'customer_id' => $kunde->customer_id, 
                    'name', => $kunde->name, 
                    'email', => $kunde->email
                ]);
           }
        }
    });
    $kundes = \DB::connection('ext_db')->table('customers')->get();
    return view('kundes.index')
        ->with('kundes', $kundes);

是的,您需要在插入客户之前进行检查。只需添加如下条件:

foreach ($all as $kunde){
    $existing_kunde = DB::connection('inn_db')->table('custoemrs')->where('customer_id', $kunde->customer_id)->first();
    if ( ! $existing_kunde) {
        DB::connection('inn_db')->table('custoemrs')->insert(
            [$kunde->customer_id
            $kunde->name,
            $kunde->email]);
   }
}

试一试,您基本上需要检查 customer table 中块的每条记录,如果不存在,则允许它们插入 customer table

public function db_update()
    {
        $customers = \DB::connection( 'ext_db' )->table( 'customers' )->orderBy( 'customer_id' )->chunk( 1000, function ( $all ) {
            foreach ( $all as $kunde ) {
                $kunde_exist = DB::connection( 'inn_db' )->table( 'customers' )
                                 ->where( [
                                     'customer_id' => $kunde->customer_id,
                                     'name'        => $kunde->name,
                                     'email'       => $kunde->email,
                                 ] )->first();
                if ( ! $kunde_exists ) {
                    DB::connection( 'inn_db' )->table( 'customers' )->insert(
                        [ $kunde->customer_id
                             $kunde->name,
                             $kunde->email]);
                  }
            }
        } );
    }