0

我在 Laravel 中使用雄辩的关系将我的数据输出到 JSON。当我使用 Eloquent Relations 时,它们在 JSON 中显示为一个对象,但我只需要 JSON 输出,其中包含没有对象或 json 的变量,如下所示:

   {
    "id": 1,
    "name": "Status changed",
    "history_id": null,
    "admin_id": 4,
    "created_at": "2021-05-21T16:10:08.000000Z",
    "updated_at": "2021-04-21T16:10:08.000000Z",
    "type_id": 2,
    "comment": "Horoshiy Specialist",
    "result_id": 2,
    "result_comment": "Prowerili anketu i obrazowanie",
    "start_time": null,
    "end_time": null,
},

而不是这个(LARVEL中一对多toJSON关系的结果):

 $activity = Activity::find(1)->load('history')->toJSON();

结果:

{
    "id": 1,
    "name": "Status changed",
    "history_id": null,
    "admin_id": 4,
    "created_at": "2021-05-21T16:10:08.000000Z",
    "updated_at": "2021-04-21T16:10:08.000000Z",
    "history": [
        {
            "id": 1,
            "type_id": 2,
            "comment": "Horoshiy Specialist",
            "result_id": 2,
            "result_comment": "Prowerili anketu i obrazowanie",
            "start_time": null,
            "end_time": null,
        }
    ]
},

任何想法如何做到这一点?我可以使用 DB join () 来做到这一点,但是有没有办法使用 Eloquent 来做到这一点?除了 :

 $activity = \App\Models\Activity::find(1)
 ->join('activity_history',  'activity_history.id', '=', 
          'activities.history_id')->select('*')->get()
 ->toJSON();

因为这不是最好的方法,因为我使用的是列名和表名,我必须去后面的DB查看它们

4

1 回答 1

0

当您获得该结果时,您可以通过展平阵列来解决此问题。让我们假设您$object->history要获得历史关系的结果,然后简单地执行以下操作:

Arr::dot($object->history);

所以你会得到一个像这样的数组:

{
    "id": 1,
    "name": "Status changed",
    "history_id": null,
    "admin_id": 4,
    "created_at": "2021-05-21T16:10:08.000000Z",
    "updated_at": "2021-04-21T16:10:08.000000Z",
    "history.id": 1,
    "history.type_id": 2,
    "history.comment": "Horoshiy Specialist",
    "history.result_id": 2,
    "history.result_comment": "Prowerili anketu i obrazowanie",
    "history.start_time": null,
    "history.end_time": null,
}
于 2021-04-23T10:23:15.413 回答