Laravel &引用;调用未定义的关系[最新发布]”;每个父级获取N个相关模型时出错

Laravel &引用;调用未定义的关系[最新发布]”;每个父级获取N个相关模型时出错,laravel,laravel-5.5,Laravel,Laravel 5.5,我有一个类别和Post模型,它们有很多关系 像这样: class Category extends Model { public function posts () { return $this->belongsToMany('App\Post', 'category_post', 'cat_id', 'post_id')->orderBy('created_at', 'desc'); } } class P

我有一个
类别
Post
模型,它们有很多关系

像这样:

class Category extends Model
{
        public function posts ()
        {
            return $this->belongsToMany('App\Post', 'category_post', 'cat_id', 'post_id')->orderBy('created_at', 'desc');
        }

}
class Post extends Model
{
    public function categories ()
    {
        return $this->belongsToMany('App\Category', 'category_post', 'post_id', 'cat_id');
    }

}
Category::with('latest_posts')
        ->whereIn('cat_id', [1,2,3,4])
        ->get();
Post
模型如下:

class Category extends Model
{
        public function posts ()
        {
            return $this->belongsToMany('App\Post', 'category_post', 'cat_id', 'post_id')->orderBy('created_at', 'desc');
        }

}
class Post extends Model
{
    public function categories ()
    {
        return $this->belongsToMany('App\Category', 'category_post', 'post_id', 'cat_id');
    }

}
Category::with('latest_posts')
        ->whereIn('cat_id', [1,2,3,4])
        ->get();
现在我想用每个类别的X帖子获取一些类别

我搜索了很多,尝试了不同的解决方案,直到我找到了。 根据该解决方案,我首先将
scopeNPerGroup
函数添加到
Category
模型中,并将此新关系添加到该模型中:

    public function latest_posts()
    {
        return $this->posts()->latest()->nPerGroup('cat_id', 3);
    }
但当我想选择一些类别并获取它们有限的帖子时,如下所示:

class Category extends Model
{
        public function posts ()
        {
            return $this->belongsToMany('App\Post', 'category_post', 'cat_id', 'post_id')->orderBy('created_at', 'desc');
        }

}
class Post extends Model
{
    public function categories ()
    {
        return $this->belongsToMany('App\Category', 'category_post', 'post_id', 'cat_id');
    }

}
Category::with('latest_posts')
        ->whereIn('cat_id', [1,2,3,4])
        ->get();
我得到了这个错误:

Call to undefined relationship [latest_posts] on model [App\Category].

除此之外,我还想创建一个动态功能,在该功能中可以发送一个
x
参数,该参数指定应获取的与计数相关的模型。

我认为这是个名副其实的问题,请尝试

public function latestPosts()
{
    return $this->posts()->latest()->nPerGroup('cat_id', 3);
}

Category::with('latest_posts')
    ->whereIn('cat_id', [1,2,3,4])
    ->get();