phpslimnotorm

NOTORM custom mysql function


How can I select a custom value calculated from an existing field ?

For example, I'm storing date of birth, and I would like to select the age, calculated from a mySql function.

$app->get("/users/:id", function ($id) use ($app, $db) {
$user = $db->users()->where("users_id", $id);
if ($data = $user->fetch()) {
    $hobbies = array();
    foreach ($data->users_hobbies() as $hobbie) { // get all tags of $application
        $hobbies[] = $hobbie["users_hobbies_name"]; // print the tag name
    }
    echo json_encode(array(
        "id" => $data["users_id"],
        "login" => $data["users_login"],
        "mail" => $data["users_mail"],
        "date_of_birth" => $data["users_date_of_birth"],
        "age" => ??
        "hobbies" => $hobbies
        ));
} else {
    echo json_encode(array(
        "status" => false,
        "message" => "User ID $id does not exist"
        ));
}
});

Solution

  • The simplest way would be to define a MySQL view with all the data you need (including the calculated age column):

    CREATE VIEW user_data AS 
    SELECT users_id, 
           users_login, 
           users_mail, 
           users_date_of_birth,
           DATE_FORMAT(NOW(), '%Y') - DATE_FORMAT(users_date_of_birth, '%Y') - (DATE_FORMAT(NOW(), '00-%m-%d') < DATE_FORMAT(users_date_of_birth, '00-%m-%d')) AS age
     FROM  users;
    

    Then you can simply query that view.

    $app->get("/users/:id", function ($id) use ($app, $db) {
    $user = $db->user_data()->where("users_id", $id);
    if ($data = $user->fetch()) {
        $hobbies = array();
        foreach ($data->users_hobbies() as $hobbie) { // get all tags of $application
            $hobbies[] = $hobbie["users_hobbies_name"]; // print the tag name
        }
        echo json_encode(array(
            "id" => $data["users_id"],
            "login" => $data["users_login"],
            "mail" => $data["users_mail"],
            "date_of_birth" => $data["users_date_of_birth"],
            "age" => $data["age"]
            "hobbies" => $hobbies
            ));
    } else {
        echo json_encode(array(
            "status" => false,
            "message" => "User ID $id does not exist"
            ));
    }
    });