How to get created data after .save()


#1

Hey guys,
following scenario: I create a new user and store them into my database. For example:

const user = new User()
user.hobby = "basketball"
user.age = 12

await user.save()

I choosed an example where the stored attributes are not unique, let’s assume the primary key is an auto increment.
The .save() method only returns true or false.

Now I want to return the saved user - but how?
I do not know the primary key and I do not have any unique values I could use for a query…

Do I miss a thing?

Kind regards,
stoniemahonie


#2

why not to try this:

 const lastUserInserted =  await User.query()
                                .orderBy('PK', 'desc')
                                .limit(1)
                                .fetch()

return lastUserInserted

I mean, build a query to fetch only one User, and how we use the orderBy() method in a desc way we can get the last one or the newest inserted

Finally to get only one we use limit(1)


#3

You can simply say user.id


#4

Thanks for your reply @ShadowPaz.
Good idea, but if I use uuids instead of auto increment, which is a common practice, this solution will not work. Also it is not 100%, because in some ways it could be possible that another user was created the same time or just right behind. This also applies to cretaedAt column.

@virk I have no clue why this is working, but it does! So thank you very much :slight_smile:


#5

While your solution works with auto incremented PKs, it seems to run in problems when using a Secure Random Hash, generated by a “beforeCreate”-Hook, as a PK.
Even the “findOrFail”-Method does not work as expected.

So “id” is defined as a string and looks like this: “46698f2bda14e249e49f6e184c88d54e110640827d7690bfa17efac2756f9277”

When I do the following:

const user = new User()
user.hobby = "basketball"
user.age = 12

await user.save()

return User.findOrFail(user.id)

It returns me an user which is definitely not the just created one proven by lookup directly in the database. Also, and this strange, it returns me always the same wrong entry.

Though there is definitely no id with the value “0”,

return User.findOrFail(0)

gives me back the same entry as above instead of throwing an exception.

How could that be? Could there be a problem by evaluating the string?


#6

You need to read the docs. When not using auto incremental ids, you have to tell the model about it by turning it off.

Just read the docs and you’ll get the answer