Laravel雄辩的hasmany-> hasmany

mar*_*kus 2 laravel eloquent

有可能在一个集合/ json中获取所有细节(用户,帖子,postimages)?

user-> hasmany(posts)post-> hasmany(postimage)

user:id | 名称

发布:id | user_id | 文本

postimage:id | post_id | imgpath

用户模型:

 public function posts() {
        return $this->hasMany('App\posts')->orderBy('id', 'ASC');
    }
Run Code Online (Sandbox Code Playgroud)

帖子模型:

public function images(){
        return $this->hasMany('App\postsimages');
    }
Run Code Online (Sandbox Code Playgroud)

从用户获取所有帖子工作正常:

$myposts = users::find(Auth::user()->id)->posts;
Run Code Online (Sandbox Code Playgroud)

我能够从循环内的帖子中获取所有图像

foreach($myposts as $mypost) {
    $postimages = $mypost->images;
}
Run Code Online (Sandbox Code Playgroud)

我想要的是获得所有帖子,没有循环的图像,例如

$myposts = users::find(Auth::user()->id)->posts->images
Run Code Online (Sandbox Code Playgroud)

谢谢

huu*_*uuk 7

是的,使用hasManyThrough关系.

帖子模型:

public function images()
{
    return $this->hasMany('App\postsimages');
}
Run Code Online (Sandbox Code Playgroud)

用户模型

public function posts()
{
    return $this->hasMany('App\posts')->orderBy('id', 'ASC');
}

public function images()
{
    return $this->hasManyThrough('App\posts', 'App\postsimages');
}
Run Code Online (Sandbox Code Playgroud)

然后

$postimages = Auth::user()->images;
Run Code Online (Sandbox Code Playgroud)