【问题标题】:issue with pagination in laravellaravel中的分页问题
【发布时间】:2018-08-12 22:42:04
【问题描述】:

我的控制器代码

$posts = Categorie::where('parent_id',$id)->paginate(2);

型号代码:

public function post1(){
    return $this->hasMany(post::class, 'category_id');
}

查看页面代码:

@foreach ($posts as $cat)
    @foreach ($cat->post1 as $post)
        {{Debugbar::info($post->body)}}
        <br>
    @endforeach
@endforeach

对于分页,我使用了代码:

{{ $posts->links() }}

一切正常,数据已获取,我在调试器中进行了检查。和分页链接也显示。我有 3 行,然后在 1 页上获取 2 行,其他页面显示另一行。但问题是,当我单击分页链接 page2 时,它会显示第 1 页上的所有数据,然后显示空白页。 我的分页如何正常工作

【问题讨论】:

  • 第二页的$cat-&gt;post1 是空的吗?
  • 您要对类别或帖子进行分页吗?
  • 我想要分页帖子

标签: php laravel pagination eloquent


【解决方案1】:

没有方法“链接”你可以试试这个

    {{ $posts->render() }}

【讨论】:

  • links() 方法只是 render() 方法的别名。但有时 links() 方法不起作用,所以尝试 render() 方法。
  • 相同的结果,渲染没有任何变化
【解决方案2】:

您目前正在对类别进行分页,而不是帖子。

定义post1的反向关系(如果你还没有):

class Post extends Model {
    public function category() {
        return $this->belongsTo(Categorie::class, 'category_id');
    }
}

然后查询Post模型并使用whereHas()

$posts = Post::whereHas('category', function($query) use($id) {
    $query->where('parent_id', $id);
})->paginate(2);

{{ $posts->links() }}
@foreach ($posts as $post)
    {{ $post->body }} 
@endforeach

【讨论】:

  • 我得到这个错误方法 Illuminate\Database\Query\Builder::category 不存在。
  • 你定义了反向关系吗?是不是叫category
  • 我听不懂你在说什么
  • 请将您的Post 模型添加到问题中。
猜你喜欢
  • 2017-11-22
  • 2018-09-09
  • 2021-05-01
  • 1970-01-01
  • 2018-07-30
  • 2016-10-02
  • 2019-08-29
  • 2019-04-19
  • 1970-01-01
相关资源
最近更新 更多