From 3bfe600c82ce340ee186fa93524144c96b9810a9 Mon Sep 17 00:00:00 2001 From: Xavier Coulon Date: Mon, 16 Jan 2017 15:50:47 +0100 Subject: [PATCH] Clarification on `DB.First(...)` method Documenting the limitation on the `func (s *DB) First(out interface{}, where ...interface{}) *DB` method where the column name is optional if the primary key is numeric. In other cases, the name of the column must be provided. --- documents/crud.md | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/documents/crud.md b/documents/crud.md index 45fecc6c..41148548 100644 --- a/documents/crud.md +++ b/documents/crud.md @@ -68,7 +68,7 @@ db.Last(&user) db.Find(&users) //// SELECT * FROM users; -// Get record with primary key +// Get record with primary key (only works for integer primary key) db.First(&user, 10) //// SELECT * FROM users WHERE id = 10; ``` @@ -150,9 +150,12 @@ db.Not(User{Name: "jinzhu"}).First(&user) **NOTE** When query with primary key, you should carefully check the value you passed is a valid primary key, to avoid SQL injection ```go -// Get by primary key +// Get by primary key (only works for integer primary key) db.First(&user, 23) //// SELECT * FROM users WHERE id = 23 LIMIT 1; +// Get by primary key if it were a non-integer type +db.First(&user, "id=?", 23) +//// SELECT * FROM users WHERE id = 23 LIMIT 1; // Plain SQL db.Find(&user, "name = ?", "jinzhu")