[英]how to display relation data into json format from two table in yii2 restful api
[英]Yii2 Restful API : display the data from database into JSON format with specific condition SQL
我正在使用Yii2 Restful API,並希望將數據顯示為JSON格式。 這是我的結構數據庫 :
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
基本上,當我在特定ID = 1( http://localhost/KDMA/web/index.php/volunteers/1 )的瀏覽器上運行時,數據將顯示如下:
{
"volunteer_id": "1",
"state_id":"12",
"nama": "Bentong",
}
結果是顯示來自自願者ID = 1的數據。 所以,我現在要做的是顯示來自state_id的數據,而不是自願者ID的數據 。 例如在SQL中:
SELECT * FROM volunteer where state_id = 12;
有什么方法可以解決我的問題?
如果我理解您的問題,我認為您可以解決以下問題:嘗試在執行所需操作的控制器中添加另一個方法,例如在自願控制器中
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.