Milos
Milos

Reputation: 602

Laravel - SQLSTATE[42S22]: Column not found: 1054 Unknown column 'categories.blog_id

So I have this error showing in my laravel project. I made blogs and categories columns in my database. My migrations: Categories:

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

Blogs:

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();
});

And these are relationships between models: My Blog model:

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

And my Category model:

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

And when I create a new blog post it shows me this error:

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)

but my blog post is stored correctly in database with category_id. What I'm doing wrong?

Upvotes: 0

Views: 597

Answers (2)

Fanan Dala
Fanan Dala

Reputation: 594

You need to add a blog_id column to your categories table. For a hasOne relationship, it is the belongsTo model that carries the id of the table it belongs to. Your code should be as follows:

Categories

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');
});

Blogs

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

Blog Model

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

Category Model

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

Upvotes: 1

RainDev
RainDev

Reputation: 1128

I think that your relations are incorrect, because one category can have many blogs

Category Model:

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

and blog belongs to one category

Blog Model:

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

Upvotes: 2

Related Questions