How do I get the Last Insert Id from a JayData tra

2019-05-31 16:24发布

问题:

Using JayData to insert a new object (record) into a Sqlite database, how do I query for the last insert id? I can do it like this but it seems inelegant:

DB.Members.orderByDescending('member.Id').take(1).toArray(function(member){    
        alert(member.Name);    
});

回答1:

If you have defined the Member class with auto-incremented Id, there is no additional query you have to write, because the Id property is filled automatically after the saveChanges().

To define a auto-incremented Id to your class, check if you have written this:

$data.Entity.extend("Member", {
    Id: { type: "int", key: true, computed: true },
    ...
});

var member = new Member();
member.Name = "a";
DB.Members.add(member);
DB.Members.saveChanges(function(){alert(member.Id);});

If the Id is set manually, your query is valid only in a scenario where the records are inserted manually by a single user of the app. We have to work out a solution together if you sync data from an online datastore.

Does it work?