【问题标题】:Laravel - SQLSTATE[42S22]: Column not found: 1054 Unknown column 'categories.blog_idLaravel - SQLSTATE [42S22]:找不到列:1054 未知列'categories.blog_id
【发布时间】:2020-06-12 16:10:56
【问题描述】:

所以我的 laravel 项目中出现了这个错误。我在我的数据库中创建了blogscategories 列。我的迁移: 分类:

Schema::create('categories', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('title');
            $table->timestamps();
});

博客:

Schema::create('blogs', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('title', 100);
            $table->string('description', 900);
            $table->string('image');
            $table->bigInteger('category_id')->unsigned();
            $table->foreign('category_id')->references('id')->on('categories');
            $table->timestamps();
});

这些是模型之间的关系: 我的Blog 模特:

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

还有我的Category 模特:

public function blogs(){
        return $this->belongsTo('App\Models\Blog', 'category_id');
}

当我创建一个新的博客文章时,它会显示这个错误:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'categories.blog_id' in 'where clause' (SQL: select * from `categories` where `categories`.`blog_id` = 16 and `categories`.`blog_id` is not null limit 1)

但我的博客文章已正确存储在category_id 的数据库中。我做错了什么?

【问题讨论】:

    标签: php mysql laravel


    【解决方案1】:

    我认为你的关系是不正确的,因为一个类别可以有很多博客

    类别模型:

    public function blogs(){
            return $this->hasMany('App\Models\Blog');
    }
    

    和博客属于一个类别

    博客模型:

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

    【讨论】:

      【解决方案2】:

      您需要将blog_id 列添加到您的categories 表中。 对于hasOne 关系,它是belongsTo 模型携带它所属的表的id。您的代码应如下所示:

      类别

      Schema::create('categories', function (Blueprint $table) {
                  $table->bigIncrements('id');
                  $table->bigInteger('blog_id')->unsigned();
                  $table->string('title');
                  $table->timestamps();
                  $table->foreign('blog_id')->references('id')->on('blogs');
      });
      

      博客

      Schema::create('blogs', function (Blueprint $table) {
                  $table->bigIncrements('id');
                  $table->string('title', 100);
                  $table->string('description', 900);
                  $table->string('image');
                  $table->timestamps();
      });
      

      博客模型

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

      类别模型

      public function blogs(){
              return $this->belongsTo('App\Models\Blog');
      }
      

      【讨论】:

      • 我通过改变模型之间的关系解决了这个问题。还是谢谢你,先生!
      猜你喜欢
      • 2018-02-21
      • 2015-12-08
      • 2018-11-02
      • 2019-10-02
      • 2017-04-03
      • 2021-10-02
      • 1970-01-01
      • 2016-01-06
      相关资源
      最近更新 更多