Returning multiple Laravel Eloquent models as JSON

白昼怎懂夜的黑 提交于 2019-12-12 09:09:54

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!