检查 Laravel 中的重复数据

JsW*_*ard 5 php mysql laravel laravel-5

此代码的工作原理是inn_db从 发送到表ext_db

但它无法检查 中的数据是否相同或不同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]);
            }
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

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

感谢@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);
Run Code Online (Sandbox Code Playgroud)

Mr.*_*mid 3

尝试一下,您基本上需要检查customer表中块的每个记录(如果不存在),然后允许它们插入customer表中

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]);
                  }
            }
        } );
    }
Run Code Online (Sandbox Code Playgroud)