2016-04-13 69 views
2

我的目標是輸出的JSON像這樣的API:格式化Laravel JSON對象與關係

[ 
    { 
     "id": 3, 
     "name": "QUbkaUJhNm", 
     "email": "[email protected]", 
     "created_at": null, 
     "updated_at": null, 
     "profile": { 
      "a": "value", 
      "b": "value", 
      "c": "value" 
     } 
    }, 
    { 
     "id": 5, 
     "name": "lYXmtkKuX9", 
     "email": "[email protected]", 
     "created_at": null, 
     "updated_at": null, 
     "profile": { 
      "a": "value", 
      "b": "value", 
      "c": "value" 
     } 
    } 
] 

我有兩個型號。

用戶模型:

public function profile() 
{ 
    return $this->hasOne(Profile::class); 
} 

的剖面模型:

public function user() 
{ 
    return $this->belongsTo(User::class); 
} 

我應該爲我的APIcontroller的代碼是什麼?

$users = User::all(); 

... 

謝謝!

回答

1

您可以使用預先加載這樣的:

return User::with('profile')->get(); 

,如果你想要的結果分頁

return User::with('profile')->paginate(); 
+0

它完美的作品,謝謝你的知識! – Eltyer