【问题标题】:Creating an json API with more than one database table创建具有多个数据库表的 json API
【发布时间】:2015-07-07 04:43:08
【问题描述】:

我正在创建一个带有食谱的 API。我有 3 个表:recipes、components 和 recipe_ingredient,其中 recipe_id 和 ingredients_id 是另外两个表的外键。

我设法从表 recipe_ingredient 中得到所有东西,它工作正常。我的问题是:我怎样才能在这个数组中得到一个包含食谱和配料信息的数组?我有点明白我必须做一种join,但我不知道怎么做我应该在我的 API 中得到它。

嗯,这很难解释,但我希望你能理解。这是我的代码:

$db = new PDO("mysql:host=localhost;dbname=recipes;charset=utf8", "root", "root");
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
$stm = $db->prepare("SELECT * FROM recipe_ingredient") ;

$stm->execute();

header('Content-Type: application/json');

while($row = $stm->fetch(PDO::FETCH_ASSOC)) {

    $api = json_encode($row, JSON_PRETTY_PRINT);
    print_r($api);

}

【问题讨论】:

  • 这3张表的返回数据取决于api会消费什么,或者说api消费者需要返回什么。

标签: php mysql json api


【解决方案1】:

你需要像这样加入表格

"SELECT * FROM recipe_ingredient left join ingredient on ingredient.id = recipe_ingredient.ingredient_id left join recipe on recipe.id = recipe_ingredient.receipe_id"

然后你可以在php中使用foreach循环来生成最终结果并使用api返回。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-16
    • 1970-01-01
    • 2013-02-09
    • 1970-01-01
    • 2018-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多