hwo to get id of last insert in nextjs/supplies

piztneat  于 2024-01-07  发布在  其他
关注(0)|答案(2)|浏览(80)

在我目前的项目中,我使用了supplies和nextjs。发生了一些奇怪的事情,在将一行插入到表中后,我想获取该行的id,但它不起作用,我不知道为什么。

import { supabase } from '../utils/supabaseClient';

export default function TestSupabase() {
    const testSupabaseConnection = async () => {
        try {
            const { data, error } = await supabase
                .from('your_table')
                .insert([{ column1: 'value1', column2: 'value2' }]);
            
            console.log('Data:', data, 'Error:', error);
        } catch (err) {
            console.error('Unexpected Error:', err);
        }
    };
    

    return (
        <div>
            <h1>Supabase Konfigurationstest</h1>
            <button onClick={testSupabaseConnection}>Teste Supabase-Verbindung</button>
        </div>
    );
}
// utils/supabaseClient.js
import { createClient } from '@supabase/supabase-js';

const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL;
const supabaseKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY;
export const supabase = createClient(supabaseUrl, supabaseKey);
{
  "name": "goatlib",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "next lint"
  },
  "dependencies": {
    "@ericblade/quagga2": "^1.8.4",
    "@heroicons/react": "^1.0.6",
    "@supabase/supabase-js": "^2.39.2",
    "next": "14.0.4",
    "react": "^18",
    "react-dom": "^18"
  },
  "devDependencies": {
    "autoprefixer": "^10.0.1",
    "eslint": "^8",
    "eslint-config-next": "14.0.4",
    "postcss": "^8",
    "tailwindcss": "^3.3.0"
  }
}

console输出是:Data: null Error: null,尽管总是插入行。上面的代码基本上不在文档中。

quhf5bfb

quhf5bfb1#

在你的查询之后,你需要像这样添加select:

const { data, error } = await supabase
.from('your_table')
.insert([{ column1: 'value1', column2: 'value2' }])
.select();

字符串
如果你只是想要的id,你可以把它包含在你选择的括号里

7dl7o3gd

7dl7o3gd2#

要实现这一点,您必须使用select()single()方法

import { supabase } from '../utils/supabaseClient';

export default function TestSupabase() {
    const testSupabaseConnection = async () => {
        try {
            const { data, error } = await supabase
                .from('your_table')
                .insert([{ column1: 'value1', column2: 'value2' }])
                .single("id") // specify the column you want returned
                .single();

            
            console.log('Data:', data, 'Error:', error);
        } catch (err) {
            console.error('Unexpected Error:', err);
        }
    };
    

    return (
        <div>
            <h1>Supabase Konfigurationstest</h1>
            <button onClick={testSupabaseConnection}>Teste Supabase-Verbindung</button>
        </div>
    );
}

字符串

相关问题