Laravel播种机-检查是否已经存在唯一的子弹

时间:2018-11-11 00:25:30

标签: laravel seeding csv-import

我正在从多个csv文件播种数据库表(“游戏”)。该表与另一个表(“控制台”)具有多对多关系。该代码适用于第一个csv文件...

我期望遇到重复(一个游戏可能会在多个平台上发布)。

我首先要检查数据库表中是否已存在记录(唯一段符),而不是错误异常, -如果已使用slug,则只需更新与现有记录的关系,将数据透视表与新控制台同步(我相信这是附加还是同步?) -如果没有-创建新记录。

模型/模式设置如下:

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateGamesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('games', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title');
            $table->string('slug')->unique();

...

一个播种器代码示例是

use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;

class SnesGamesSeeder extends Seeder
{
    public function run()
    {

        // Fetch the data from our CSV File
        $data = $this->seedFromCSV(base_path('/database/seeds/csvs/snes-csv-filtered.csv'), ',');

        foreach ($data as $game)
        {
            $title = $game['Title'];
            $slug = Str::slug($title)
            $date = strtotime($game['release_date']);
            $format_date = date('Y-m-d',$date);

            DB::table('games')->insert(
                [
                    'title' => $title,
                    'slug' => $slug,
                    'release_date' => $format_date,

...

我希望能够做类似的事情

   foreach ($data as $game)
   {
     $title = $game['Title'];
     $slug = Str::slug($title)
     **if(*** $slug already exists in 'game' table){
       (find ID) -> ->consoles()->attach(5);
     } else {**
       DB::table('games')->insert(
         [
           'title' => $game['Title'],
           'slug' => Str::slug($game['Title']),
           'release_date' => $format_date,

...

0 个答案:

没有答案