亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Laravel - SQLSTATE [42S22]:找不到列:1054 未知列

Laravel - SQLSTATE [42S22]:找不到列:1054 未知列

PHP
哆啦的時光機 2023-05-26 16:00:07
所以我的 laravel 項目中顯示了這個錯誤。我在我的數據庫中創建了blogs列categories。我的遷移:類別: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。我做錯了什么?
查看完整描述

2 回答

?
郎朗坤

TA貢獻1921條經驗 獲得超9個贊

我認為你的關系不正確,因為一個類別可以有很多博客

分類型號:

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

和博客屬于一類

博客模型:

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


查看完整回答
反對 回復 2023-05-26
?
森林海

TA貢獻2011條經驗 獲得超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');

}


查看完整回答
反對 回復 2023-05-26
  • 2 回答
  • 0 關注
  • 299 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號