Implementing 1:N relationships with JayData

Create a new northwind product with an existing category

HTML

<script src="http://include.jaydata.org/jaydata.js"></script>

JavaScript

//Define the Category entity with the Products array property
$data.Entity.extend("Category", {
    Id: { key: true, type: "int", computed: true },
    Name: { type: "string", required: true },
    Products: { type: Array, elementType: "Product", inverseProperty: "Category" } 
});

//Define the Product entity with the Category reference
$data.Entity.extend("Product", {
    Id: { key: true, type: "int", computed: true },
    Name: { type: "string", required: true },
    Category: { type: "Category", inverseProperty: "Products" }
});

//Define our context to 
$data.EntityContext.extend("NorthwindContext", {
    Categories: { type: $data.EntitySet, elementType: Category },
    Products: { type: $data.EntitySet, elementType: Product }
});

//Initialize a WebSQL/SQLite database connection with the defined schema
var nw = new NorthwindContext({ provider: "webSql", databaseName: "northwind" });

nw.onReady(function () {
    //create new category instance
    var newDep = new Category({ Name: 'Food' });
    //add the new category to the context
    nw.Categories.add(newDep);
    //save the new category to the WebSQL database
    nw.saveChanges(function () {
        //query the persisted category from the database by the Name property
        nw.Categories.first("it.Name == 'Food'", {}, function (cat) {
            //attach the existing category to the context to track changes and avoid persisting it again
            nw.Categories.attach(cat);
            //create a new product
            var prod = new Product({
                Name: 'Bread',
                Category: cat //set the existing category
            });

            //add the new product to the context
            nw.Products.add(prod);
            //save the new product to the database
            nw.Products.saveChanges(function () {
                //read all the products from the DB with the related Category reference
                //without the include() oparator JayData doens't load the navigation...