【问题标题】:Pagination in laravel with limit record带有限制记录的laravel分页
【发布时间】:2021-06-11 02:20:34
【问题描述】:

我是 Laravel 的新手如何向 getRelatedNews 函数添加分页我需要在分页视图中显示简单的“下一个”和“上一个”链接,我尝试使用 simplePaginate 方法我不知道该函数放在哪里?

public function news($id, $alias)

{
    $crypto_news = CryptoNews::where('id', $id)->first();
    if(isset($crypto_news->title)) {
        $data = [
            'crypto_news' => $crypto_news,
            'crypto_related_news' => $this->getRelatedNews($id,100),
            'crypto_most_read_news' => $this->getMostReadNews($id, 7, 6),
            'crypto_news_from_bitcoin' => $this->getNewsFromBitcoin($id, 9)
        ];
        return view(getCurrentTemplate() . '.pages.single_news', $data);
    }
    return redirect('/crypto-coins-news-headlines');
}

public function getRelatedNews($id, $limit)
{
    $crypto_news = CryptoNews::take($limit)
        ->where('status', '=', 1)
        ->where('urlToImage', '!=', 'no_preview.png')
        ->where('urlToImage', '!=', '')
        ->where('lang', 'en')->where('id', '!=', $id)
        ->orderBy('publishedAt', 'desc')->get()->toArray(); 
    $lang_news = [];            
    if(LaravelLocalization::getCurrentLocale() != 'en') {
        $news_object = CryptoNews::take($limit)
            ->where('status', '=', 1)
            ->where('urlToImage', '!=', 'no_preview.png')
            ->where('urlToImage', '!=', '')->where('id', '!=', $id)
            ->where('lang', LaravelLocalization::getCurrentLocale())
            ->orderBy('publishedAt', 'desc');
        if($news_object->count() > 0) {
            $lang_news = $news_object->get()->toArray();
        }
        if($news_object->count() > $limit) {
            $crypto_news = $lang_news;
        } else {
            $crypto_news = array_merge($lang_news, array_slice($crypto_news, 0, $limit-$news_object->count()));
        }
    }
    return $crypto_news;
}

【问题讨论】:

  • laravel.com/docs/8.x/pagination 请参考此链接。希望您从官方文档中获得解决方案。您必须在查询响应中仅添加 paginate() 方法。
  • 我收到此错误 (2/2) ErrorException 在我使用 $crypto_news = CryptoNews::where('status', '=', 1) ->where 后遇到格式不正确的数值('urlToImage', '!=', 'no_preview.png') ->where('urlToImage', '!=', '') ->where('lang', 'en')->where('id ', '!=', $id) ->orderBy('publishedAt', 'desc')->simplePaginate($limit);

标签: php laravel pagination


【解决方案1】:

如果您正在实现分页,则不需要take() 方法。引用官方文档:

take 方法返回具有指定数量项目的新集合。

要使用simplePaginate,您可以在查询中像这样使用它:

$crypto_news = CryptoNews::where('status', '=', 1)
    ->where('urlToImage', '!=', 'no_preview.png')
    ->where('urlToImage', '!=', '')
    ->where('lang', 'en')->where('id', '!=', $id)
    ->orderBy('publishedAt', 'desc')->simplePaginate($limit);

【讨论】:

  • 我收到此错误 (2/2) ErrorException 遇到格式不正确的数值
  • @muhammedalsmawi 如果我猜一下,您的 $limit 变量一定不是数字。 simplePaginate() 方法将整数作为参数。请检查,如果错误仍然存​​在,请提供完整的堆栈跟踪/调试日志,以便正确调试。
猜你喜欢
  • 2023-04-09
  • 2021-08-07
  • 2021-10-17
  • 1970-01-01
  • 2022-10-18
  • 2016-09-06
  • 1970-01-01
  • 2015-01-27
  • 1970-01-01
相关资源
最近更新 更多