Skip to content

Aliases as foreing keys with sample code

marios88 edited this page Jun 28, 2018 · 2 revisions

Assume we have a table "users" and table "page" and want to save who created it and who made the last edit

Initialise R::

if(!R::testConnection()){
    $aliases = array();
    $aliases[] = array('editedfrom'=> 'users');
    $aliases[] = array('createdfrom'=> 'users');
    R::aliases($aliases);
    R::setup("mysql:host=".$hostname.";dbname=".$database,$username,$password);
    if(ENVIRONMENT === 'development'){
        R::debug( TRUE, 3 );
    }
}

Aside from the usual init, we also called R::aliases that practically "translates" the relations

So now you can have this code on the "add page"

$page = R::dispense('page');
....
$page->createdtime = date('Y-m-d H:i:s')
$page->createdfrom = R::load('users',$users_id);
$id = R::store($page);

On the edit Page

$page = R::load('page',$page_id);
...
$page->editedtime = date('Y-m-d H:i:s');
$page->editedfrom = R::load('users',$users_id);
$id = R::store($page);