ответ с вложенным форматом Json - PullRequest
0 голосов
/ 02 июля 2019

Я пытаюсь получить ответ в виде вложенного формата 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 не такой, как я ожидал

Ответы [ 2 ]

0 голосов
/ 04 июля 2019

Я не знаю, есть ли такая опция для реализации этого поведения только с запросом. Но вы можете реализовать связное отношение к отношениям шагов и добавить шаги с помощью методов 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();

В результате вы получаете структуру данных, которую вы описали.

0 голосов
/ 02 июля 2019

Вам нужно выполнить запрос с помощью 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();
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...