我用Laravel写了这段代码:
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)
的某个地方失败了。
我该怎么办?
发布于 2018-12-07 04:31:34
分页方法适用于雄辩的模型。检索模型,首先应用whereIn,然后对其进行分页。试试这个:
public function index() {
$user = auth()->user();
$validPosts = $user->posts()->whereIn('status', ['Pending', 'Processing'])->paginate(5);
return view('home', $validPosts);
}
现在在你的“主页”视图文件中,你可以使用$validPosts
发布于 2018-12-07 05:15:50
你可以试试这种方式。
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]);
}
或者你可以这样做
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]);
}
希望这能对你有所帮助。
https://stackoverflow.com/questions/53659081
复制相似问题