Yii2 Restful API: mapping data from a database to JSON format with a specific SQL condition

I am working on a Yii2 restful API and want to display data in JSON format. This is my structure database :

TABLE `volunteer`(
`volunteer_id` int(11) NOT NULL auto_increment,
`state_id` int(11) null
`nama` varchar(200) null

TABLE `state`(
`state_id` int(11) NOT NULL auto_increment,
`state` varchar(225) null

Basically, when I run in a browser with a specific ID = 1 ( http: //localhost/KDMA/web/index.php/volunteers/1 ), the data will be displayed as follows:

{
   "volunteer_id": "1",
   "state_id":"12",
   "nama": "Bentong",
}

this result displays data from volunteer_id = 1. So, now I want to show data from state_id, not volunteer_id . For example, in SQL:

SELECT * FROM volunteer where state_id = 12;

What are the ways to solve my problem?

+1
source share
1 answer

, , : , , , Controller

public function actionViewByState ($ id)
   {

     if (($ model = State :: findOne ($ id))! == null) {
         $ this-> setHeader (200);
     echo json_encode (array ('status' => 1, 'date' => array_filter ($ model-> attributes)), JSON_PRETTY_PRINT);
     } Else {

       $ this-> setHeader (400);
       echo json_encode (array ('status' => 0, 'error_code' => 400, 'message' => 'Bad request'), JSON_PRETTY_PRINT);
       exit;
     }
   }

  http: //localhost/KDMA/web/index.php/volunteers/view-by-state/1
0

Source: https://habr.com/ru/post/1589115/


All Articles