我遇到了将两个表中的数据显示为 JSON 格式并使用 yii2 restful api 的问题。
这是我的结构数据库:
TABLE `volunteer`(
`volunteer_id` int(11) NOT NULL auto_increment,
`state_id` int(11) null
TABLE `state`(
`state_id` int(11) NOT NULL auto_increment,
`state` varchar(225) null
volunteerController.php
public $modelClass = 'app\models\Volunteer';
public function behaviors()
{
return ArrayHelper::merge(parent::behaviors(),[
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['post'],
],
],
]);
}
config/web.php
'rules' => [
['class' => 'yii\rest\UrlRule', 'controller' => ['volunteer','state','post']],
],
'request' => [
// !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
'cookieValidationKey' => 'QMoK0GQoN7_VViTXxPdTISiOrITBI4Gy',
'parsers' => [
'application/json' => 'yii\web\JsonParser',
],
],
这是 JSON 格式的结果:
[
{
"volunteer_id": 1,
"country_id": 1,
"state_id": 12,
}
]
所以结果不是我想要的。我想要的是 state_id 应该从表 state 返回状态数据,这意味着 state : New York 。不返回 state_id。如何解决这个问题呢 ?
最佳答案
这可以通过重写 fields()
来完成:
public function fields()
{
return [
'volunteer_id',
'country_id',
'state' => function ($model) {
return $model->state->name; // Return related model property, correct according to your structure
},
];
}
此外,您可以使用 with()
在 prepareDataProvider()
方法中加载此关系。
官方文档:
关于php - 如何从yii2 restful api中的两个表将关系数据显示为json格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30363574/