我正在Laravel 5中构建一个API,希望获得我喜欢的人员名单及其信息。
class User extends Model implements AuthenticatableContract, CanResetPasswordContract {
use Authenticatable, CanResetPassword;
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'users';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = ['username', 'email', 'password'];
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = [
'password',
'secret_key'
];
public function attribute()
{
return $this->hasOne('App\UserAttributes', 'user_id', 'id');
}
public function photos()
{
return $this->hasMany('App\Photos', 'user_id', 'id');
}
public function favourites()
{
return $this->hasMany('App\Favourites', 'from', 'id');
}
public function favourited()
{
return $this->hasMany('App\Favourites', 'to', 'id');
}
class Favourites extends Model {
protected $table = 'favourite';
public function user()
{
return $this->belongsTo('App\User', 'from', 'id');
}
}
class UserAttributes extends Model {
protected $table = 'user_attributes';
public function user()
{
return $this->belongsTo('User', 'user_id', 'id');
}
}
From
是我的用户ID,to
是我用过的用户ID。这就是我目前所拥有的:
return User::with(['attribute','favourites'])->find($user_id);
我想要实现的目标类似于以下内容:
"favourites": [
{
"id": "15",
"from": "231", // My ID
"to": "**100**", // ID of user I have favourited (FK)
"created_date": "2013-04-10 21:35:28",
"user": [
"id": "**100**", // USER ID
"username": "someuser",
"email": "random@mail.com",
"email_verified": "1",
"has_photo": "1",
"dob": "1952-11-12"
],
"attribute": [
"id": "105",
"user_id": "**100**", // USER ID (FK)
"height": "70",
"car": "0",
"pet": "2",
]
}
]
我需要上面的json,这样当我在我的应用程序或网站中调用api URL / api / v1 / favorites?my_id = 231并获取所有必需的信息而不是单独加载它们。除非我错了?
如果您认为这种方式对于某个应用来说是错误的,我会非常乐意听到您的意见,因为这对我来说是新的。
答案 0 :(得分:0)
您确实需要在发送之前转换数据。您可能想要创建函数或类' UserTransformer'那会为你做的。 Fractal可能会对您有所帮助。如果你是Laracasts的粉丝或Laravel的新手,你肯定错过了增量API系列(https://laracasts.com/series/incremental-api-development)。