使用 Laravel 以所需方式构建 JSON 对象

Building JSON object in desired way with Laravel

各位同事大家好,

我在构建 json 输出结构时遇到了问题。 我想要的是以下输出:

{
  comments: {
        data: {
            created_at: "date",
            other: "etc",
        from: {
            username: "navidos",
            user_id: 1
         }
       }
    }
}

但是现在构建的方式是:

{
    data: {
        description: "post description",
        status: "public",
        link: "http://www.bla.com",
        created_at: "2015-01-23 00:00:00",
    comments: [
    {
          text: "comment text 1",
          date: "2015-01-23 18:30:00",
          id: 1
     },
     {
          text: "comment text 2",
          date: "2015-01-23 18:35:00",
          id: 2
      },
      {
          text: "comment text 3",
          date: "2015-01-23 19:00:00",
          id: 3
       }
],
       user: {
           user_id: 1,
           username: "navid",
           profile_picture: null,
           bio: null
        }
    }
}

我得到的输出几乎没问题,但我希望此输出中的注释部分像第一个输出一样。我已经尝试了 array_merge 和数组推送的所有方法,但无法弄清楚我在这里做错了什么。有没有人可以帮助我。我正在使用 Laravel 4 并与 Eloquent ORM 建立关系。

所以在我的路线中,我现在有以下内容。

$post = Post::find($id);
$postComments = $post->comments;
$usersPost = $post->user;

return Response::json(
   $data = array('data'=>$post)
);

如果有人能帮助我解决这个问题,我将不胜感激。先进的Tnx。

您可以简单地将您与 User 的关系命名为 Comment from():

public function from(){
    return $this->belongsTo('User');
}

然后预加载 commentsfrom:

$post = Post::with('comments.from')->find($id);

结果应该是这样的:

{
    description: "post description",
    status: "public",
    link: "http://www.bla.com",
    created_at: "2015-01-23 00:00:00",
    comments: [
        {
            text: "comment text 1",
            date: "2015-01-23 18:30:00",
            id: 1,
            from: {
                user_id: 1,
                username: "navid",
                profile_picture: null,
                bio: null
            }
        }
        // next comment
    ]
}

如果您想在 JSON 输出中隐藏其中一些属性,您可以将它们添加到模型中的 $hidden 数组中:

class Comment extends Eloquent {
    protected $hidden = ['id'];
}

我目前的 Post.php 模型是:

//An post belongs to an user
    public function user(){
        return $this->belongsTo('User')->select(array('user_id', 'username','profile_picture','bio'));
    }

    //An post has many comments
    public function comments(){
        return  $this->hasMany('Comment')->select(array('comment as text','date','comment_id as id'));  
    }

我的 Comment.php 模型看起来像:

//An post belongs to an user
    public function user(){
        return $this->belongsTo('User')->select(array('user_id', 'username','profile_picture','bio'));
    }

我的 User.php 模型看起来像:

public function from(){
        return $this->hasMany('comments');   
    }

在我的路线中,现在我有如下建议:

$post = Post::with('comments.from')->find($id);

但这会引发错误: Illuminate\Database\Query\Builder::from()

缺少参数 1

我有没有做错什么?