Мне нужны данные LawfirmName (та, которая вводит в таблицу LawyersContactProfiles, продукты и веб -сайты), прилегающие к любым другим данным, были вставлены одновременно. < /p>
Например, если я импортирую CSV в таблицу: Продукты - Столбная: Вход вместо прилегания к другим данным, которые представлены.
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);
}
}
Upload CSV Final Test
Import CSV
{#if headers.length}
{#each columnMappings as mapping, index}
{mapping.header}
Select table
{#each Object.keys(tableColumns) as table}
{table}
{/each}
{#if mapping.table && tableColumns[mapping.table]}
Select column
{#each tableColumns[mapping.table] as column}
{column}
{/each}
{/if}
{/each}
Insert Data
{/if}
Подробнее здесь: https://stackoverflow.com/questions/794 ... adjacent-r
Данные таблицы иностранных ключей помещаются в отдельные строки вместо соседних рядов (Sveltekit и Supabase) ⇐ Html
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение
-
-
Когда использовать столбец JSON против таблицы иностранных ключей? [закрыто]
Anonymous » » в форуме C# - 0 Ответы
- 5 Просмотры
-
Последнее сообщение Anonymous
-
-
-
Исключение отображения иностранных ключей в Hibernate: несоответствие столбцов
Anonymous » » в форуме JAVA - 0 Ответы
- 9 Просмотры
-
Последнее сообщение Anonymous
-