phpnotorm

NotORM foreign key data not picked up


This is my first introduction with NotORM and I'm unable to print foreignkey data. Here are my tables:

**userinfo**
id , int (primary key, autoincrement)
username , varchar(50)
gender , varchar(6)
password , varchar(50)

**budgetinfo**
entryid , int (primary key, autoincrement)
userid int references userinfo(id)
amount , varchar(50)
entrydate , varchar(6)

Here is my NotORM code:

<?php

require "NotORM.php";

$dsn = "mysql:dbname=budget;host=127.0.0.1";
$pdo = new PDO ( $dsn, "root", "root" );
$budgetdb = new NotORM ( $pdo );
?>

The code lists the records but didn't print the budgetinfo entry.

Where have I gone wrong?

<br/><br/>
<hr/>
Listing records, userinfo(id) => pk , budgetinfo(userid) => fk
<hr/>

<?php 
$userinfos = $budgetdb->userinfo();

if(isset($userinfos) && count($userinfos)>0){
    foreach ( $userinfos as $userinfo ) {
        echo $userinfo ["username"] . " " . $userinfo ["gender"] . "<br/>";

        $budgets = $userinfo->budgetinfo();

        if(isset($budgets) && count($budgets)>0){
            foreach ($budgets as $budget)
                echo $budget->budgetinfo["amount"] . " , " . $budget->budgetinfo["entrydate"] . "<br/>";
        }
        else
            echo "No budgets set...";

        echo "<br/>-------------------------------<br/>";
    }
}
else
    echo "No record found...";
?>

Solution

  • The actual problem seems to be that your tables' primary_id do not match the NotORM standard convention. The easiest way to fix this problem is to change the budgetinfo's entryid to simply id and change userid to user_id. This way you have conformed to NotORM's method to hint relationships.

    If you have the relationships defined in MySQL, you can use the auto-discovery feature to obtain the relationship structure.

    $structure = new NotORM_Structure_Discovery($pdo, $cache = null, $foreign = '%s');
    

    When declaring new NotORM($pdo), add an additional argument for $structure.

    If you do not have the relationships defined in MySQL, you are in deep trouble as I can only point out that you should visit http://www.notorm.com/#identifiers to help you out. Look at the area:

    class UserStructure extends NotORM_Structure_Convention {
        function getReferencedTable($name, $table) {
            if ($name == "created_by" || $name == "modified_by") {
                return "user";
            }
            return parent::getReferencedTable($name, $table);
        }
    }
    
    $structure = new UserStructure;