【问题标题】:how to skip if rows exist如果行存在如何跳过
【发布时间】:2020-04-02 14:57:08
【问题描述】:

嗨,我是 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'));
}

【问题讨论】:

标签: php laravel


【解决方案1】:

查看文档Determining If Records Exist

使用

->doesntExist();

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-07
    • 2019-06-23
    • 2019-09-28
    • 1970-01-01
    • 2017-11-29
    • 1970-01-01
    • 2018-10-21
    • 1970-01-01
    相关资源
    最近更新 更多