首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >User::find($user_id)的Laravel分页问题

User::find($user_id)的Laravel分页问题
EN

Stack Overflow用户
提问于 2018-12-07 04:20:10
回答 2查看 681关注 0票数 0

我用Laravel写了这段代码:

代码语言:javascript
复制
public function index()
{
    $user_id = auth()->user()->id; // gets the current user id
    $user = User::find($user_id); // find the specific user id

    $validPosts = $user->posts->paginate(5)->whereIn('status', ['Pending', 'Processing']);
    return view('home', compact('validPosts'));
}

我希望返回所有具有挂起的status的帖子,并使用值为5的分页进行处理,但我得到了以下错误:

方法Illuminate\Database\Eloquent\Collection::paginate不存在。

我知道我在$user->posts->paginate(5)的某个地方失败了。

我该怎么办?

EN

回答 2

Stack Overflow用户

发布于 2018-12-07 04:31:34

分页方法适用于雄辩的模型。检索模型,首先应用whereIn,然后对其进行分页。试试这个:

代码语言:javascript
复制
public function index() {
    $user = auth()->user();
    $validPosts = $user->posts()->whereIn('status', ['Pending', 'Processing'])->paginate(5);

    return view('home', $validPosts); 
}

现在在你的“主页”视图文件中,你可以使用$validPosts

票数 4
EN

Stack Overflow用户

发布于 2018-12-07 05:15:50

你可以试试这种方式。

代码语言:javascript
复制
public function index()
{
    $user_id = auth()->user()->id; // gets the current user id
    $user = User::find($user_id); // find the specific user id


    // paginate function should be last
    $validPosts = $user->posts()->whereIn('status', ['Pending', 'Processing'])->paginate(5);


    // if you want to pass more variable, do it like this
    return view('home', ['validPosts' => $validPosts]);
}

或者你可以这样做

代码语言:javascript
复制
public function index()
{
    $user_id = auth()->user()->id; // gets the current user id 


    // paginate function should be last
    $validPosts = Post::where('user_id', $user_id)->whereIn('status', ['Pending', 'Processing'])->paginate(5);


    // if you want to pass more variable, do it like this
    return view('home', ['validPosts' => $validPosts]);
}

希望这能对你有所帮助。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53659081

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档