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

北慕城南 提交于 2019-12-13 01:33:21

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/30410577/yii2-restful-api-display-the-data-from-database-into-json-format-with-specific

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!