【问题标题】:Laravel Join Relations for JSONJSON 的 Laravel 连接关系
【发布时间】:2021-07-17 10:51:24
【问题描述】:

我在 Laravel 中使用 Eloquent 关系将我的数据输出到 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查看它们

【问题讨论】:

  • 欢迎来到 SO .. 你可以使用 laravel 模型和关系
  • 这是雄辩关系的预期输出。如果你想以某种方式格式化它,你必须在控制器中手动组装数组。

标签: mysql json laravel eloquent laravel-relations


【解决方案1】:

当你得到这个结果时,你可以通过展平数组来解决这个问题。让我们假设你$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,
}

【讨论】:

  • 真是个了不起的人!像该死的一样工作。请您分享源代码,您的代码中有一个小错误 Arr::dot($object->toArray());
猜你喜欢
  • 1970-01-01
  • 2021-01-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-22
  • 1970-01-01
  • 2019-05-08
  • 2018-06-02
相关资源
最近更新 更多