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

问题描述 投票:0回答:2

亲爱的同事们大家好,

我在构建 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 和 array push 的所有方法,但无法弄清楚我在这里做错了什么。有没有人可以帮助我。我正在使用 Laravel 4 并与 Eloquent ORM 建立关系。

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

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

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

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

php arrays json laravel laravel-4
2个回答
1
投票

您可以简单地将您与

User
的关系命名为
Comment
from()
:

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

然后立即加载

comments
from
:

$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'];
}

0
投票

我的 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

我有什么做得不对的地方吗?

© www.soinside.com 2019 - 2024. All rights reserved.