【发布时间】: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消费者需要返回什么。