【问题标题】:Paginate a One to Many Relationship为一对多关系分页
【发布时间】:2015-11-25 16:22:42
【问题描述】:

我有一个模型TopicPost

每个Topic 都有很多Post

我的 Topic 模型通过 Post 的一对多关系扩展了 Eloquent。

class Topic extends Eloquent
{

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

}

我的 Post 模型也扩展了 Eloquent。

class Post extends Eloquent
{

    public function topic()
    {
        return $this->belongsTo('Post');
    }

}

在我的TopicController 中,我想通过这种关系对我的帖子进行分页。我花费了这样的东西会起作用:

$topic->posts->paginate(20);

但是,它是一个Collection 对象。因此,我收到以下错误消息。

调用未定义的方法 Illuminate\Database\Eloquent\Collection::paginate()

如何正确分页一对多关系?

【问题讨论】:

    标签: php laravel laravel-4 orm eloquent


    【解决方案1】:

    这里的问题是$topic->posts$topic->posts() 不同。而前者是Illuminate\Database\Eloquent\Collection 对象。后者是一个Illuminate\Database\Eloquent\Relations\HasMany 对象。

    因此,以下将起作用。

    $topic->posts()->paginate(20);
    

    【讨论】:

    • 如何使用渲染功能打印数字?
    • 好的,我找到方法了`$topic->posts()->paginate(10)->render()`
    • 这个方法有个缺点,Eager Loading 不起作用。如何使用 ->with() ?
    猜你喜欢
    • 1970-01-01
    • 2019-10-02
    • 2015-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-19
    • 1970-01-01
    • 2018-12-07
    相关资源
    最近更新 更多