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 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀