问题
My "user" model with a has-many relationship to an "image" model.
Returning just the user is as easy as "return Response::eloquent($user);". I'd like to either return a JSON array of {user: {id:…}, images: [{id:…},{id:…}]} or, perhaps better, {id:…, images: [{id:…},{id:…}]}
What's the best way to arrange and ship these models? Should I
回答1:
The first thing you'll need to do is make sure your models are set up correctly:
class Users extends Eloquent {
public function images()
{
return $this->hasMany('Image');
}
}
class Image extends Eloquent {
public function user()
{
return $this->belongsTo('User');
}
}
Then in your route you should be able to do something like:
Route::any('userinfo/{$userId}', function($userId)
{
return Response::json(User::with('images')->find($userId));
//or
return User::with('images')->find($userId)->toJson();
});
来源:https://stackoverflow.com/questions/15821563/returning-multiple-laravel-eloquent-models-as-json