Php 如何在yii2restfulapi中从两个表将关系数据显示为json格式
我遇到了将两个表中的数据显示为JSON格式并使用Yi2 restful api的问题 这是我的结构数据库:Php 如何在yii2restfulapi中从两个表将关系数据显示为json格式,php,json,rest,yii2,relation,Php,Json,Rest,Yii2,Relation,我遇到了将两个表中的数据显示为JSON格式并使用Yi2 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 unvoriteControlle
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
unvoriteController.php
public $modelClass = 'app\models\Volunteer';
public function behaviors()
{
return ArrayHelper::merge(parent::behaviors(),[
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['post'],
],
],
]);
}
'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',
],
],
config/web.php
public $modelClass = 'app\models\Volunteer';
public function behaviors()
{
return ArrayHelper::merge(parent::behaviors(),[
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['post'],
],
],
]);
}
'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\u id应该从表state返回状态数据,这意味着state:newyork。不返回状态号。如何解决此问题 这可以通过如下方式重写
字段()
来完成:
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()
方法中加载此关系
官方文件:
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
public function setOtherAttr($state_id){
if (($model = State::find()->where(['state_id'=>$state_id])->all()) !== null) {
return $model;
} else {
return '';
}
}
我不理解'state'=>function($model){return$model->state->name;//返回相关的模型属性,根据您的结构更正},该代码实际放在哪里?您是否通过我提供的链接阅读了文档?应该在ActiveRecord模型中完成。好的。。我得到了它。我替换了return$model->states->state及其100%工作状态。谢谢你的关心,我不使用你提供的文件。我刚刚创建了另一个函数公共函数getStates(){return$this->hasOne(State::className(),['State\u id'=>'State\u id']);}很高兴能提供帮助。如果答案解决了你的问题,你可以接受。