Foreign Key table data is being placed in in separate rows instead of adjacent rows (SvelteKit and Supabase) - Stack Overflow

admin2025-04-17  1

I need the lawfirmname data (the one that enters the lawyerscontactprofiles, products, and websites) table adjacent to any other data has been inserted at the same time.

For example, if I import a csv to the table: products - column: lawfirm, the lawfirmname column (which has a foreign key relationship to the lawfirm table) data is being created as a separate entry instead of adjacent to the other data that is submitted.

I need the lawfirmname data to be in the same row, so I can refer it in my app and ensure that data (the product data, for example) is linked to that particular lawfirm.

The app is being written in Svelte, and is connected to my Supabase Database

<script>
  import Papa from "papaparse";
  import { supabase } from "../../../lib/supabaseClient";


  const tableColumns = {
    lawfirm: [
      "lawfirmname",
      "clientstatus",
      "websiteurl",
      "address1",
      "address2",
      "city",
      "stateregion",
      "postalcode",
      "country",
      "phonenumber",
      "emailaddress",
      "description",
      "numberofemployees",
    ],
    lawyerscontactprofiles: [
      "firstname",
      "lastname",
      "email",
      "phone",
      "profilepicture",
      "position",
      "accountemail",
      "accountphone",
      "addressline1",
      "suburb",
      "postcode",
      "state",
      "country",
      "website",
      "lawfirmname",
    ],
    products: [
      "websitedevelopment",
      "websitehosting",
      "websitemanagement",
      "newsletters",
      "searchengineoptimisation",
      "socialmediamanagement",
      "websiteperformance",
      "advertising",
      "lawfirmname",
    ],
    websites: ["url", "dnsinfo", "theme", "email", "lawfirmname"],
  };

  let file,
    headers = [],
    data = [],
    columnMappings = [];

  $: headers = [...headers];
  $: data = [...data];
  $: columnMappings = [...columnMappings];

  async function handleFileChange(event) {
    try {
      file = event.target.files[0];
      if (!file) throw new Error("No file selected.");
      console.log("File selected:", file);
    } catch (err) {
      console.error("File selection error:", err.message);
      alert(err.message);
    }
  }

  async function handleFileUpload() {
    if (!file) {
      alert("Please select a file to upload.");
      return;
    }

    const reader = new FileReader();
    reader.onload = (event) => {
      const csvData = event.target.result;
      Papa.parse(csvData, {
        header: true,
        skipEmptyLines: true,
        complete: (results) => {
          headers = results.meta.fields;
          data = results.data;
          columnMappings = headers.map((header) => ({
            header,
            table: "",
            column: "",
          }));
        },
        error: (err) => console.error("Error parsing CSV:", err),
      });
    };

    reader.readAsText(file);
  }

  async function handleDataInsert() {
    const tables = {
      lawfirm: [],
      lawyerscontactprofiles: [],
      products: [],
      websites: [],
    };

    data.forEach((row) => {
      const lawfirmname = row["lawfirmname"]?.trim() || "";
      const rowTables = new Set(); 

      columnMappings.forEach(({ header, table, column }) => {
        if (table && column) {
          if (column === "lawfirmname" && table === "lawfirm") {
            tables.lawfirm.push({ lawfirmname: row[header]?.trim() || "" });
          } else {
            const tempRecord = {};
            tempRecord[column] = row[header]?.trim() || "";
            if (column === "lawfirmname") {
              tempRecord["lawfirmname"] = lawfirmname;
            }
            if (Object.keys(tempRecord).length > 0) {
              tables[table].push(tempRecord);
              rowTables.add(table); 
            }
          }
        }
      });
    });

    const uniqueLawfirms = [];
    const seenLawfirms = new Set();
    tables.lawfirm.forEach((obj) => {
      if (!seenLawfirms.has(obj.lawfirmname)) {
        seenLawfirms.add(obj.lawfirmname);
        uniqueLawfirms.push(obj);
      }
    });
    tables.lawfirm = uniqueLawfirms;

    try {
      for (const table in tables) {
        if (tables[table].length > 0) {
          const { error } = await supabase.from(table).upsert(tables[table], {
            onConflict: table === "lawfirm" ? ["lawfirmname"] : undefined,
          });
          if (error) {
            console.error(`Error inserting into ${table}:`, error.message);
          } else {
            console.log(`Successfully inserted into ${table}`);
          }
        }
      }
    } catch (error) {
      console.error("Error inserting data:", error.message);
    }
  }
</script>

<div class="homeBanner">
  <h1 class="leftAlign">Upload CSV Final Test</h1>
  <div class="searchAndAdd">
    <input type="file" accept=".csv" on:change={handleFileChange} />
    <button on:click={handleFileUpload}>Import CSV</button>
  </div>
</div>

{#if headers.length}
  <div class="mappingSection">
    {#each columnMappings as mapping, index}
      <div class="mappingRow">
        <label for="table-{index}">{mapping.header}</label>
        <select id="table-{index}" bind:value={mapping.table}>
          <option value="">Select table</option>
          {#each Object.keys(tableColumns) as table}
            <option value={table}>{table}</option>
          {/each}
        </select>
        {#if mapping.table && tableColumns[mapping.table]}
          <select id="column-{index}" bind:value={mapping.column}>
            <option value="">Select column</option>
            {#each tableColumns[mapping.table] as column}
              <option value={column}>{column}</option>
            {/each}
          </select>
        {/if}
      </div>
    {/each}
    <button class="insertButton" on:click={handleDataInsert}>Insert Data</button
    >
  </div>
{/if}

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1744857189a270899.html

最新回复(0)