【问题标题】:Column not found: 1054 Champ 'posts.categorie_id' inconnu未找到列:1054 Champ 'posts.category_id' inconnu
【发布时间】:2019-12-01 06:52:07
【问题描述】:

我想从 CATEGORIE 中获取 POSTS,我建立了 HasMany/belongsTo 关系,但它给了我错误。

Categorie.php

public function posts(){
        return $this->hasMany('App\Post');
    }

Post.php

public function category(){
        return $this->belongsTo('App\Category');
    }

SiteController.php

public function getPostsOfCategory($slug){

        $categorie=Categorie::where('slug',$slug)->first();
        $posts= $categorie->posts()->paginate(4);
        $categories=Categorie::all();

        return view('site.blog',['posts'=>$posts,'categories'=>$categories]);
    }

【问题讨论】:

    标签: php laravel voyager


    【解决方案1】:

    首先你调用模型Categorie,但使用Category

    return $this->belongsTo('App\Category');
    

    ->

    return $this->belongsTo('App\Categorie');
    

    这可能不是完整的解决方案。

    然后检查帖子表中的外键列的名称。并将其更改/添加到数据库中或作为第二个参数传递给belongsTo() 关系。

    【讨论】:

      【解决方案2】:

      错误在于您的 SiteController

      public function getPostsOfCategory($slug)
      {
      
              $categorie=Categorie::where('slug',$slug)->first();
              $posts= $categorie->posts;
              $categories=Categorie::all();
      
              return view('site.blog',['posts'=>$posts,'categories'=>$categories]);
      
       }
      

      【讨论】:

      • property ->posts 返回没有分页方法的集合。
      • 对。错过了。谢谢。
      • 控制器没有错误。
      猜你喜欢
      • 1970-01-01
      • 2020-09-13
      • 1970-01-01
      • 1970-01-01
      • 2015-02-22
      • 2017-07-23
      • 1970-01-01
      • 2016-04-09
      相关资源
      最近更新 更多