Laravel:合并两个表中的数据

时间:2017-04-26 12:45:35

标签: php laravel-5.4

我有一个与职业,技能,名称,位置等有关系的用户表。我可以使用此命令app\users::find(1)及其技能信息(例如app\user::find(1)->skill)获得简单的用户信息。如何使用单个命令获取有关特定用户的一般信息,专业信息,技能信息?

例如:

  

本地主机:8000 /用户/ 1

此链接应该给我json结果如下:

{
  "id": 0,
  "name": "string",
  "email": "string",
  "gender": "string",
  "age": 0,
  "mobile_number": "string",
  "company_name": "string",
  "verification_status": 0,
  "image_url": "string",
  "joining_date": "2017-04-26T12:34:34.501Z",
  "message": "string",
  "profession": {
    "id": 0,
    "name": "string"
  },
  "designation": {
    "id": 0,
    "name": "string"
  },
  "location": {
    "id": 0,
    "longitude": 0,
    "latitude": 0,
    "address": "string",
    "city": "string",
    "country": "string"
  },
  "interests": [
    {
      "id": 0,
      "name": "string",
      "custom": "string"
    }
  ],
  "skills": [
    {
      "id": 0,
      "name": "string",
      "custom": "string"
    }
  ]
}

1 个答案:

答案 0 :(得分:1)

您可以加载该模型的所有关系using eager loading,然后加载serialize that object to a json string

像这样:

app\user::where('id', 1)->with(['profession', 'designation', '...'])->first()->toJson();