簡體   English   中英

使用單個變量查詢“id”或“slug”

[英]Make a query to both “id” or “slug” with a single variable

我有一個表格“文章”,其中有“id”和“slug”等。 在 html 頁面上,我有一個文章鏈接列表。 鏈接中可以包含“id”或“slug”。

但是,如果在 URL 中只有一個數字,這並不意味着它是一個 id——因此,轉換為 int 來確定它是 slug 還是 id 是行不通的。

  /articles/my_article
  /articles/35 
  /articles/666 --> still may be slug

我有這個 sql 查詢:

import (
  "github.com/jackc/pgx/v4"
  //.........
)


// [..........]


vars := mux.Vars(req)
q1 := `
  SELECT
    ar.id,
    [.........]
  FROM
    articles AS ar
  WHERE ar.slug = $1 OR ar.id = $1`

ar := Article{}
row := db.QueryRow(context.Background(), q1, vars["id_or_slug"])
switch err := row.Scan(&ar.Id, /*[.......]*/); err {
case pgx.ErrNoRows:
  wrt.WriteHeader(http.StatusNotFound)
  wrt.Write([]byte("article not found"))
case nil:
  // good, article found

我得到:

ERROR: operator does not exist: bigint = text (SQLSTATE 42883)

您可以“嘗試”將該值轉換為 integer,如果轉換失敗,只需忽略錯誤並提供一個已知在數據庫中存在的 id 值。

使用 Go 進行轉換:

slug := mux.Vars(req)["id_or_slug"]

// option 1:
id, err := strconv.ParseInt(slug, 10, 64)
if err != nil {
    id = -1 // provide a value that you're certain will not be present in the db
}

// option 2:
// if id 0 is good enough, you can skip error checking
// and use the following instead of the above.
id, _ := strconv.ParseInt(slug, 10, 64)

query := `SELECT ... FROM articles AS a
WHERE a.slug = $1
OR a.id = $2`

row := db.QueryRow(query, slug, id)

使用 postgres 進行轉換:(以下 postgres 片段取自此處。)

-- first create a postgres function that will do the conversion / cast
create or replace function cast_to_int(text, integer) returns integer as $$
begin
    return cast($1 as integer);
exception
    when invalid_text_representation then
        return $2;
end;
$$ language plpgsql immutable;

...然后在 go 中使用它:

slug := mux.Vars(req)["id_or_slug"]

query := `SELECT ... FROM articles AS a
WHERE a.slug = $1
OR a.id = cast_to_int($1::text, -1)` // use the postgres function in the go query string

row := db.QueryRow(query, slug)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM