我有一个yii2模型和关系 Yii2响应格式设置为JSON 我想用它的关系(一对多)返回模型,到目前为止一切都很好。
但是,在这种情况下,对于模型关系之一,JSON响应编码为JSON对象{},而不是array []。我无法弄清楚究竟是为什么?对于其他关系,它是一个数组。
下面是模型的var_dump。有问题的关系是items
/backend/controllers/TasksController.php:181:
object(app\models\Task)[163]
private '_attributes' (yii\db\BaseActiveRecord) =>
array (size=6)
'id' => int 9
'title' => string 'Sample dnewsd' (length=13)
'mode' => string 'onlyads' (length=7)
'deployed' => int 0
'start_time' => string '2017-11-16 00:00:00' (length=19)
'end_time' => null
private '_oldAttributes' (yii\db\BaseActiveRecord) =>
array (size=6)
'id' => int 9
'title' => string 'Sample dnewsd' (length=13)
'mode' => string 'onlyads' (length=7)
'deployed' => int 0
'start_time' => string '2017-11-16 00:00:00' (length=19)
'end_time' => null
private '_related' (yii\db\BaseActiveRecord) =>
array (size=3)
'items' =>
array (size=2)
0 =>
object(app\models\TaskItem)[178]
...
2 =>
object(app\models\TaskItem)[201]
...
'devices' =>
array (size=0)
empty
'deviceGroups' =>
array (size=0)
empty
这是我编辑模型时的JSON返回:
{
"status": "ok",
"data": {
"id": 9,
"title": "Sample task",
"mode": "onlyads",
"deployed": 0,
"start_time": "2017-11-16 00:00:00",
"end_time": null,
"items": {
"0": {
"id": 2,
"image_url": "/media/lightboxes/pictures/ad_.jpg",
"duration": 20,
"task_id": 9
},
"2": {
"id": 46,
"image_url": "/media/lightboxes/pictures/ad_46.jpg",
"duration": 20,
"task_id": 9
}
},
"devices": [],
"deviceGroups": []
}
}
您可以看到项目不是JSON数组:items : {}
在另一个操作中 - 获取相同的模型,返回的JSON具有items: []
:
{
"status": "ok",
"data": {
"id": 9,
"title": "Sample dnewsd",
"mode": "onlyads",
"deployed": 0,
"start_time": "2017-11-16 00:00:00",
"end_time": null,
"items": [
{
"id": 2,
"image_url": "/media/lightboxes/pictures/ad_.jpg",
"duration": 20,
"task_id": 9
},
{
"id": 46,
"image_url": "/media/lightboxes/pictures/ad_46.jpg",
"duration": 20,
"task_id": 9
}
],
"devices": [],
"deviceGroups": []
}
}
以下是GET操作中相同模型的var_dump:
/srv/www/erp-ang/backend/controllers/TasksController.php:55:
object(app\models\Task)[163]
private '_attributes' (yii\db\BaseActiveRecord) =>
array (size=6)
'id' => int 9
'title' => string 'Sample dnewsd' (length=13)
'mode' => string 'onlyads' (length=7)
'deployed' => int 0
'start_time' => string '2017-11-16 00:00:00' (length=19)
'end_time' => null
private '_oldAttributes' (yii\db\BaseActiveRecord) =>
array (size=6)
'id' => int 9
'title' => string 'Sample dnewsd' (length=13)
'mode' => string 'onlyads' (length=7)
'deployed' => int 0
'start_time' => string '2017-11-16 00:00:00' (length=19)
'end_time' => null
private '_related' (yii\db\BaseActiveRecord) =>
array (size=3)
'items' =>
array (size=2)
0 =>
object(app\models\TaskItem)[178]
...
1 =>
object(app\models\TaskItem)[184]
...
'devices' =>
array (size=0)
empty
'deviceGroups' =>
array (size=0)
empty
任何线索为什么会发生这种情况?
答案 0 :(得分:1)
数组需要有从0开始的连续索引,
如果你需要重新索引已加载的关系,你可以运行
$task->populateRelation('items', array_values($task->items));