1
0
mirror of https://github.com/astaxie/beego.git synced 2025-07-03 17:10:18 +00:00

Add a ReadOrCreate method:

m := &User{Name: "Kyle"}
// Returns a boolean indicating whether the object was created,
// the primary key of the object, or an error.
created, id, err := orm.ReadOrCreate(m, "Name")
This commit is contained in:
Kyle McCullough
2014-01-21 23:58:57 -06:00
parent edf7982567
commit 190039b6f8
3 changed files with 53 additions and 0 deletions

View File

@ -74,6 +74,20 @@ func (o *orm) Read(md interface{}, cols ...string) error {
return nil
}
// Try to read a row from the database, or insert one if it doesn't exist
func (o *orm) ReadOrCreate(md interface{}, col1 string, cols ...string) (bool, int64, error) {
cols = append([]string{col1}, cols...)
mi, ind := o.getMiInd(md, true)
err := o.alias.DbBaser.Read(o.db, mi, ind, o.alias.TZ, cols)
if err == ErrNoRows {
// Create
id, err := o.Insert(md)
return (err == nil), id, err
}
return false, ind.Field(mi.fields.pk.fieldIndex).Int(), err
}
// insert model data to database
func (o *orm) Insert(md interface{}) (int64, error) {
mi, ind := o.getMiInd(md, true)