How to fix error Base table or view not found: 1146 Table laravel relationship table?

五迷三道 提交于 2021-01-26 03:10:36

问题


I am a new of laravel I try to create relationship many to many between table,My problem when I am insert data in to database I got errors

QueryException in Connection.php line 713: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'learn.category_posts' doesn't exist (SQL: insert into category_posts (category_id, posts_id) values (4, ))

can anyone help me pls . and here below is my migrate and code:

2016_08_04_131009_create_table_posts.php

public function up()
{
    Schema::create('posts', function (Blueprint $table) {
        $table->increments('id');
        $table->text('title');
        $table->text('body');
        $table->timestamps();
    });
}

2016_08_04_131053_create_table_categories.php

public function up()
{
    Schema::create('categories', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->timestamps();
    });
}

2016_08_04_131413_create_table_category_posts.php

public function up()
{
    Schema::create('category_post', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('category_id')->unsigned();
        $table->integer('post_id')->unsigned();
        $table->foreign('category_id')->references('id')->on('categories')->onUpdate('cascade')->onDelete('cascade');
        $table->foreign('post_id')->references('id')->on('posts')->onUpdate('cascade')->onDelete('cascade');
        $table->timestamps();
    });
}

and my model Posts.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Posts extends Model
{
    protected $table = 'posts';

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

Category.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    protected $table = 'categories'; 

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

My PostsController.php

public function create()
{
    $categories = Category::all();
    return view('create',compact('categories'));
}

public function store(Request $request)
{
   $post = new Posts;
   $post->title = $request->title;
   $post->body = $request->body;
   $post->categories()->attach($request->categories_id);

    return redirect()->route('posts.index');
}

My View create.blade.php

{!!Form::open(array('route' => 'store', 'method' => 'POST'))!!}

    {{Form::text('title')}}<br>
    {{Form::textarea('body')}}<br>
    <select name="categories_id" multiple>
        @foreach ($categories as $category)
            <option value="{{ $category->id }}">{{ $category->name }}</option>
        @endforeach
    </select>
    <br>
    {{Form::submit('submit')}}

{!!Form::close()!!}

回答1:


It seems Laravel is trying to use category_posts table (because of many-to-many relationship). But you don't have this table, because you've created category_post table. Change name of the table to category_posts.




回答2:


Laravel tries to guess the name of the table, you have to specify it directly so that it does not give you that error..

Try this:

class NameModel extends Model {
    public $table = 'name_exact_of_the_table';

I hope that helps!




回答3:


Schema::table is to modify an existing table, use Schema::create to create new.




回答4:


The main problem for causing your table unable to migrate, is that you have running query on your "AppServiceProvider.php" try to check your serviceprovider and disable code for the meantime, and run php artisan migrate




回答5:


You can add this in Post Model,

public function categories()
{
 return $this->belongsToMany('App\Category','category_post','post_id','category_id');                 
}

category_post indicate the table you want to use.
post_id indicate the column where you want to store the posts id.
category_id indicate the column where you want to store the categories id.




回答6:


The simplest thing to do is, change the default table name assigned for the model. Simply put following code, protected $table = 'category_posts'; instead of protected $table = 'posts'; then it'll do the trick.

However, if you refer Laravel documentation you'll find the answer. Here what it says,

By convention, the "snake case", plural name of the class(model) will be used as the table name unless another name is explicitly specified

Better to you use artisan command to make model and the migration file at the same time, use the following command,

php artisan make:model Test --migration

This will create a model class and a migration class in your Laravel project. Let's say it created following files,

Test.php

2018_06_22_142912_create_tests_table.php

If you look at the code in those two files you'll see,

2018_06_22_142912_create_tests_table.php files' up function,

 public function up()
 {
      Schema::create('tests', function (Blueprint $table) {
      $table->increments('id');
      $table->timestamps();
      });
 }

Here it automatically generated code with the table name of 'tests' which is the plural name of that class which is in Test.php file.




回答7:


For solving your Base Table or view not found error you can do As @Alexey Mezenin said that change table name category_post to category_posts,

but if you don't want to change the name like in my case i am using inventory table so i don't want to suffix it by s so i will provide table name in model as protected $table = 'Table_name_as_you_want' and then there is no need to change table name:

Change your Model of the module in which you are getting error for example:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Inventory extends Model
{
    protected $table = 'inventory';

    protected $fillable = [
        'supply', 'order',
    ];
}

you have to provide table name in model then it will not give error.




回答8:


You should change/add in your PostController: (and change PostsController to PostController)

public function create()
{
    $categories = Category::all();
    return view('create',compact('categories'));
}

public function store(Request $request)
{
    $post = new Posts;
    $post->title = $request->get('title'); // CHANGE THIS
    $post->body = $request->get('body'); // CHANGE THIS
    $post->save(); // ADD THIS
    $post->categories()->attach($request->get('categories_id')); // CHANGE THIS

    return redirect()->route('posts.index'); // PS ON THIS ONE
}

PS: using route() means you have named your route as such

Route::get('example', 'ExampleController@getExample')->name('getExample');

UPDATE

The comments above are also right, change your 'Posts' Model to 'Post'




回答9:


try checking in the app if you are using the tables before it's created such as appServiceProvider.php

you might be calling the table without being created it, if you are, comment it then run php artisan migrate.




回答10:


This problem occur due to wrong spell or undefined database name. Make sure your database name, table name and all column name is same as from phpmyadmin




回答11:


If you're facing this error but your issue is different and you're tired of searching for a long time then this might help you.

If you have changed your database and updated .env file and still facing same issue then you should check C:\xampp\htdocs\shopsees\bootstrap\cache\config.php file and replace or remove the old database name and other changed items.



来源:https://stackoverflow.com/questions/38770785/how-to-fix-error-base-table-or-view-not-found-1146-table-laravel-relationship-t

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!