我正在尝试将我的响应作为嵌套的json格式
[
{
"recipe_id":"33",
"e_name":"crispy",
"e_desc":"Crispy Gingersnaps",
"calries":"500",
"steps":[
{
"step_id":"22",
"recipe_id":"33",
"step_number":3,
"instruction":'here is the instructions',
}
{
"step_id":"23",
"recipe_id":"34",
"step_number":4,
"instruction":'here is the instructions',
}
{
"step_id":"23",
"recipe_id":"35",
"step_number":5,
"instruction":'here is the instructions',
}
]
}
]
这是我的代码
$query = new \yii\db\Query();
$recipes = $query->select(['recipe.recipe_id','recipe.image','recipe.'.$name,'recipe.'.$small_desc,'recipe.person_count',
'recipe.calories','recipe.period','recipe.'.$desc,'recipe_step.instruction'])->from('recipe')
->where(['recipe.recipe_id' => $recipe_id])
->innerJoin("recipe_step","recipe.recipe_id=recipe_step.recipe_id");
我得到结果,但是json格式不符合我的预期
答案 0 :(得分:0)
我不知道是否存在仅通过查询实现此行为的选项。但是您可以实现与步骤关系的接受关系,并使用yii2方法添加步骤。
食谱模型
public function getStep()
{
return $this->hasMany(Step::className(), ['recipe_id' => 'id']);
}
您希望在哪里获得
$model = Recipe::find()->where([Recipe::tableName() . '.id' => $recipe_id])->innerJoin('step')->asArray()->one();
因此,您获得了已描述的数据结构。
答案 1 :(得分:-1)
您需要使用all()执行查询,以在查询结束时获得期望的结果。
$recipes = $query->select(['recipe.recipe_id','recipe.image','recipe.'.$name,'recipe.'.$small_desc,'recipe.person_count',
'recipe.calories','recipe.period','recipe.'.$desc,'recipe_step.instruction'])->from('recipe')
->where(['recipe.recipe_id' => $recipe_id])
->innerJoin("recipe_step","recipe.recipe_id=recipe_step.recipe_id")->all();