Skip to content

Commit 21fe7c7

Browse files
gheckenbachgheckenbachmz
authored andcommitted
Use last field of a compound PK when setting auto ids
1 parent 427c1bd commit 21fe7c7

File tree

2 files changed

+12
-4
lines changed

2 files changed

+12
-4
lines changed

lapis/db/mysql/model.lua

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -136,8 +136,12 @@ do
136136
local res = db.insert(self:table_name(), values, self:primary_keys())
137137
if res then
138138
local new_id = res.last_auto_id or res.insert_id
139-
if not values[self.primary_key] and new_id and new_id ~= 0 then
140-
values[self.primary_key] = new_id
139+
local pk = self.primary_key
140+
if type(pk) == "table" then
141+
pk = pk[#pk]
142+
end
143+
if not values[pk] and new_id and new_id ~= 0 then
144+
values[pk] = new_id
141145
end
142146
return self:load(values)
143147
else

lapis/db/mysql/model.moon

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -33,8 +33,12 @@ class Model extends BaseModel
3333
-- either luasql (field res.last_auto_id) or
3434
-- lua-resty-mysql (field res.insert_id) and
3535
new_id = res.last_auto_id or res.insert_id
36-
if not values[@primary_key] and new_id and new_id != 0
37-
values[@primary_key] = new_id
36+
pk = @primary_key
37+
-- In a compound primary key, the auto_increment field must be last.
38+
if type(pk) == "table"
39+
pk = pk[#pk]
40+
if not values[pk] and new_id and new_id != 0
41+
values[pk] = new_id
3842
@load values
3943
else
4044
nil, "Failed to create #{@__name}"

0 commit comments

Comments
 (0)