1

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

例如,我正在存储出生日期,并且我想选择从 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"
        ));
}
});
4

1 回答 1

1

最简单的方法是使用您需要的所有数据(包括计算列)定义一个 MySQL 视图: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"
        ));
}
});
于 2013-02-27T09:31:15.503 回答