NOTORM自定义mysql函数

时间:2013-02-20 15:25:37

标签: php slim notorm

如何选择从现有字段计算的自定义值?

例如,我正在存储出生日期,我想选择从mySql函数计算的年龄。

$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"
        ));
}
});

1 个答案:

答案 0 :(得分:1)

最简单的方法是define a MySQL view包含您需要的所有数据(包括计算的age列):

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;

然后您可以简单地查询该视图。

$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"
        ));
}
});