简体   繁体   中英

Yii2 Restful API : display the data from database into JSON format with specific condition SQL

I'm working on Yii2 restful API and want to display the data into 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 at browser with specific ID = 1 ( http://localhost/KDMA/web/index.php/volunteers/1 ) the data will display like this:

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

that result is display the data from volunteer_id = 1. So, what I want to do right now is display the data from state_id, not volunteer_id . For example in SQL:

SELECT * FROM volunteer where state_id = 12;

What are the ways that can solve my problem?

If I understand your question I think you can solve the problem as follows: try adding another method in the controller that performs the action you need eg in volunteerController

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;
     }
   }

and then call the action with

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM