如何跳过是否存在行

时间:2019-12-09 13:32:50

标签: php laravel

嗨,我是laravel的新手。

我已经尝试使用laravel建立某种形式的领先管理CRM。

转到Google Sheet API,并在每次页面刷新时从那里获取所有记录。

问题是创建重复记录,
并且如果在先前刷新之前已经存在的记录上使用->unique()其致命错误“重复输入”。

我想要的是一种仅保存不存在的记录的方法

架构

    Schema::create('leads', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->unsignedBigInteger('user_id');
        $table->string('name');
        $table->string('email')->unique();
        $table->string('tel');
        $table->string('type')->nullable();;
        $table->string('status')->nullable();;
        $table->string('reject')->nullable();;
        $table->timestamps();
    });

控制器

 public function index(Request $request, User $user) 
 {
    $client = new Google_Client();
    putenv('GOOGLE_APPLICATION_CREDENTIALS=../att-sheets-b5343f28dd39.json');
    $client->useApplicationDefaultCredentials();
    $client->addScope(Google_Service_Drive::DRIVE);

    $driveService = new Google_Service_Drive($client);

    // List Files
    // $response = $driveService->files->listFiles();

    // Set File ID and get the contents of your Google Sheet
    $fileID = '1okqjGbGDnbzJbXDwZ1A6RHJ3LddyL6fGMZWnq88xUiw';
    $response = $driveService->files->export($fileID, 'text/csv', array(
          'alt' => 'media'));
    $content = $response->getBody()->getContents();

    // Create CSV from String
    $csv = Reader::createFromString($content, 'r');
    $csv->setHeaderOffset(0);
    $records = $csv->getRecords();

    // Create an Empty Array and Loop through the Records
    $newarray = array();
    foreach ($records as $value) {
        $newarray[] = $value;
    }

    foreach ($newarray as $data) {
        auth()->user()->leads()->create([
            'name'  => $data['your-name'],
            'tel'   => $data['your-tel'],
            'email' => $data['your-email']
        ]);
    }

    return view('leads.index', compact('newarray'));
}

1 个答案:

答案 0 :(得分:-2)

检查文档Determining If Records Exist

使用

->doesntExist();

如果您想检查数据库中是否存在该记录