将多个Laravel Eloquent模型作为JSON返回 [英] Returning multiple Laravel Eloquent models as JSON

查看:52
本文介绍了将多个Laravel Eloquent模型作为JSON返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的用户"模型与图像"模型有很多关系.

My "user" model with a has-many relationship to an "image" model.

仅返回用户就像"return Response :: eloquent($ user);"一样容易.我想返回一个JSON数组 {user:{id:…},图片:[{id:…},{id:…}]} 或者,也许更好 {id:…,图片:[{id:…},{id:…}]}

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

推荐答案

您需要做的第一件事是确保正确设置模型:

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();
});

这篇关于将多个Laravel Eloquent模型作为JSON返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆