duanci1939 2016-11-19 18:06
浏览 38
已采纳

返回所有用户的每个用户的帖子和每个帖子的评论laravel

I am using laravel eloquent and I made models (User,Post,Comment)

the relaitions is

User model

public function posts(){
    return $this->hasMany('App\Post');
}

public function comments(){
    return $this->hasMany('App\Comment');
}

Post model

public function comments()
{
    return $this->hasMany('App\Comment');
}
public function user()
{
    return $this->belongsTo('App\User');
}

Comment model

public function post()
{
    return $this->belongsTo('App\Post');
}

I Want to return all users and each user has an object of his posts and each post of those has an object of all comments

I have this query

$users = \App\User::with('posts')->\get();
return $users;

it returns objects of users and each user have object of his posts, but no comments object

now the problem is

in php, e.g. I can return user[0]->posts[0]->coments() and it return the comments

but I can not see this comments in javascript or mobile phones as API it returns "try to get property of non object"

so .. I want to use the comments in js or API

I can get the comments using for loop but I looking for better solution

  • 写回答

1条回答 默认 最新

  • duan0514324 2016-11-19 18:08
    关注

    You can do it like this:

    $users = \App\User::with('posts', 'posts.comments')->get();
    return $users;
    

    Hope this helps!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试,帮帮忙吧
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建