[英]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. 我正在使用Yii2 Restful API,并希望将数据显示为JSON格式。 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: 基本上,当我在特定ID = 1( http://localhost/KDMA/web/index.php/volunteers/1 )的浏览器上运行时,数据将显示如下:
{
"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 . 结果是显示来自自愿者ID = 1的数据。 所以,我现在要做的是显示来自state_id的数据,而不是自愿者ID的数据 。 For example in SQL:
例如在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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.