CreateReadUpdateDelete : Defining a 1:1 relation

Create 2 entities and connect them.

by SchizoDuckie

HTML

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="https://schizoduckie.github.io/CreateReadUpdateDelete.js/src/CRUD.js"></script>
<script src="https://schizoduckie.github.io/CreateReadUpdateDelete.js/src/CRUD.SqliteAdapter.js"></script>
<div class="well"><h1>CreateReadUpdateDelete : Defining a 1:1 relation</h1>
    <p>Example 1:1 relationship</p>

   <button id="wipe">Wipe database</button>

JavaScript

CRUD.DEBUG = true;
// checkout the console to see debug info by CRUD.SqliteAdapter.js

if(!'openDatabase' in window) {
    alert("Your inferior browser does not support WebSQL. Try Chrome(ium), Safari, Opera, or any other Webkit based browser.");
}

function Role() {
    CRUD.Entity.call(this);
}

function Actor() {
    CRUD.Entity.call(this);
}

CRUD.define(Role, {
    table: 'Roles', 
    primary: 'ID_Role',
    fields: [ // List all individual properties including primary key. Accessors will be auto-created (but can be overwritten)
        'ID_Role',
        'name',
        'ID_Actor'
    ],
    relations: {
        	'Actor' : CRUD.RELATION_SINGLE
    },
    createStatement: 'CREATE TABLE Roles (ID_Role INTEGER PRIMARY KEY NOT NULL, name VARCHAR(250) DEFAULT(NULL), ID_Actor INTEGER NULL)'
});

CRUD.define(Actor, {
    table: 'Actors', 
    primary: 'ID_Actor',
    fields: [ // List all individual properties including primary key. Accessors will be auto-created (but can be overwritten)
        'ID_Actor',
        'firstName',
        'lastName',
        'gender',
        'ID_Role'
    ],
    relations: {
        	'Role' : CRUD.RELATION_SINGLE
    },
    createStatement: 'CREATE TABLE Actors (ID_Actor INTEGER PRIMARY KEY NOT NULL, firstname VARCHAR(250) DEFAULT(NULL), lastname VARCHAR(250) DEFAULT(NULL), gender CHAR(250) DEFAULT(NULL), ID_Role INTEGER NULL)'
});


// initialize WebSQL database connection
CRUD.setAdapter(new CRUD.SQLiteAdapter('createreadupdatedelete_single', {
    estimatedSize: 25 * 1024 * 1024
})).then(function() {

    var cptn = new Role();
    cptn.name = 'Captain Jack Sparrow';

    var actor = new Actor();
    actor.firstName = 'Johnny';
    actor.lastName = 'Depp';
    actor.gender = 'm';

    cptn.Connect(actor);

});

// drop tables on click and reload page 
document.getElementById('wipe').onclick = function() {
    CRUD.executeQuery('drop table Actors').then(
    CRUD.executeQuery('drop table Roles')).then(
        function()...