0
votes

I cant figure out what the problem is, the 2 tables are not connecting for some reason, I read many articles and tried many things still not working.

I want to link post and category tables together, so when I can display the category chosen in the post made.

  public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->increments('id');
            $table->timestamps();
            $table->string('name');
            $table->text('description');
            $table->integer('category_id');
            $table->integer('price');
            $table->integer('currency_id');
        });
    }

Category

 public function up()
    {
        Schema::create('categories', function (Blueprint $table) {
            $table->id();
            $table->timestamps();
            $table->string('name');
            $table->bigInteger('post_id')->unsigned();
            $table->foreign('post_id')->references('id')->on('posts');
        });
    }

This is the error I get:

SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'categories' already exists (SQL: create table categories (id bigint unsigned not null auto_increment primary key, created_at timestamp null, updated_at timestamp null, name varchar(255) not null, post_id bigint unsigned not null) default character set utf8mb4 collate 'utf8mb4_unicode_ci')

1
What command do you use for the migration?Dan
probable your database has an existing table categoriesDeepak
i know, even when i dropped the table and migrate it again it does not workHarout
can you try removing $table->foreign('post_id')->references('id')->on('posts'); if this works.Deepak
I guess your Database migration files are wrong order. The first file for posts then categories.Deepak

1 Answers

0
votes

Try refreshing you database entirely using the migrate:refresh artisan command.

php artisan migrate:refresh --seed

It may be that a database migration ran and failed before it could register in the migrations table of your database.


Issues: (so far)

1) As per above, a migrate:refresh sorts out the original error

2) $table->bigInteger('post_id')->unsigned(); will not work as posts.id is an integer and not a bigInteger.

Solution:

Change your post_id definition to

$table->integer('post_id')->unsigned();