【问题标题】:Method Illuminate\Database\Eloquent\Collection方法 Illuminate\Database\Eloquent\Collection
【发布时间】:2023-03-13 05:58:02
【问题描述】:

我想在刀片中使用分页显示文章,但出现以下错误。 不用分页也没问题。

BadMethodCallException 方法 Illuminate\Database\Eloquent\Collection::links 不存在。 (看法: c:\xampp\htdocs\blog\resources\views\frontend\tag.blade.php)


    public function tag($slug)
    {
        $tag = Tag::where('slug', $slug)->first() ?? abort(404);
        $articles =  Article::where('status', '=', '1')->paginate(5);
        $article = $tag->articles;
        return view('frontend.tag', compact('article'));
    }

前端/tag.blade.php:

    {{ $article->links() }}

型号:Article.php



     public function articles()
      {
        return $this->belongsToMany(Article::class);
      }

【问题讨论】:

  • 您会在集合 $articles->links() 上调用方法 links,而不是在单个对象上。

标签: laravel


【解决方案1】:

你打错电话了。在你的刀片中应该是$article->links() 而不是article->links()。你在article 中错过了$

 {{ $article->links() }}

同样在你的控制器中删除 $article = $tag->articles; 。因为这个替换分页结果来自第一个查询,它应该是

$articles =  Article::whereHas('tags',function($query)use($slug){$query->where('slug', $slug)})->where('status', '=', '1')->paginate(5);

最终的解决方案是

public function tag($slug)
{
    $articles =  Article::whereHas('tags',function($query)use($slug){
    $query->where('slug', $slug)})->where('status', '=', '1')->paginate(5);
              
     return view('frontend.tag', compact('article'));
}

在文章模型中添加关系

public function tags()
      {
        return $this->belongsToMany(Tag::class);
      }

分页视图

 {{ $article->links() }}
       

【讨论】:

  • 使用此代码 $article = $tag->articles;显示与特定标签相关的文章。公共函数articles() { return $this->belongsToMany(Article::class); }
  • 这段代码有效。但不显示分页此代码 {{ $article->links() }} 在我的文件中但不显示分页
  • 显示有问题的控制器和刀片的完整代码。更新
【解决方案2】:

在你的刀片文件中,你正在做{{ article->links() }}。所以你使用 $article 变量就像一个集合

但是,在您的控制器(刀片之前的代码)中,$articles 是具有分页的变量。

您只能在 Paginator 上调用 ...->links()(在您的情况下,这是 $articles 变量)。您不能在集合上调用...->links()(在您的情况下,$article 是一个集合——$tag->articles 的集合)

更新:我假设您没有错过{{ article->links() }}article 变量的$。否则,您应该收到不同类型的叫喊(解析错误)

【讨论】:

  • 使用此代码 $article = $tag->articles;显示与特定标签相关的文章。公共函数articles() { return $this->belongsToMany(Article::class); }
  • 你的意图不明确。在frontend/tag.blade.php中,是要显示带有status = 1的文章的分页链接,还是要显示带有slug = $slugstatus = 1标签的文章的分页链接?
猜你喜欢
  • 2018-10-22
  • 2020-11-21
  • 2021-09-08
  • 2020-11-13
  • 2019-12-11
  • 2020-02-04
  • 2019-11-12
  • 2019-05-24
  • 2019-09-04
相关资源
最近更新 更多