如何修复错误 Base table or view not found: 1146 Table laravel 关系表?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38770785/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 17:29:20  来源:igfitidea点击:

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

laravellaravel-5laravel-5.2

提问by He7nG

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

我是laravel的新手我尝试在表之间创建多对多关系,当我将数据插入数据库时​​出现错误

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, ))

Connection.php 第 713 行中的 QueryException: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'learn.category_posts' does not 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

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

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

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

和我的模型 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

<?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

我的 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

我的视图 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()!!}

回答by Alexey Mezenin

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

似乎 Laravel 正在尝试使用category_poststable(因为多对多关系)。但是你没有这个表,因为你已经创建了category_post表。将表的名称更改为category_posts.

回答by jpasosa

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

Laravel 试图猜测表的名称,你必须直接指定它,这样它就不会给你那个错误..

Try this:

尝试这个:

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

I hope that helps!

我希望这有帮助!

回答by Shal

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

Schema::table就是修改一个现有的表,Schema::create用来创建新的。

回答by Aldrin Masamoc Mojica

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

导致您的表无法迁移的主要问题是您在“AppServiceProvider.php”上运行查询尝试检查您的serviceprovider代码并同时禁用代码,然后运行php artisan migrate

回答by Anand Mainali

You can simply fix the problem adding this in Post Model,

您可以简单地解决在Post Model 中添加此问题的问题,

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

category_postindicate the table you want to use.
post_idindicate the column where you want to store the posts id.
category_idindicate the column where you want to store the categories id.

category_post指明您要使用的表。
post_id指示要存储帖子 ID 的列。
category_id指示要存储类别 ID 的列。

回答by Chathura D Ranathunga

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.

最简单的方法是更改​​为模型分配的默认表名。只需输入以下代码, protected $table = 'category_posts';而不是protected $table = 'posts';然后它就可以解决问题。

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

但是,如果您参考 Laravel 文档,您会找到答案。这里说的是,

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,

最好使用 artisan 命令同时制作模型和迁移文件,使用以下命令,

php artisan make:model Test --migration

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,

这将在你的 Laravel 项目中创建一个模型类和一个迁移类。假设它创建了以下文件,

Test.php

测试文件

2018_06_22_142912_create_tests_table.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.phpfiles' up function,

2018_06_22_142912_create_tests_table.php文件的 up 函数,

 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.phpfile.

这里它自动生成了表名“tests”的代码,这是Test.php文件中那个类的复数名称。

回答by luis

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

如果您在创建之前使用表(例如 appServiceProvider.php),请尝试签入应用程序

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

您可能会在没有创建它的情况下调用该表,如果是,请对其进行注释,然后运行 ​​php artisan migrate。

回答by Haritsinh Gohil

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

为了解决您的基表或视图未找到错误,您可以按照@Alexey Mezenin 所说的将表名更改category_postcategory_posts

but if you don't want to change the name like in my case i am using inventorytable so i don't want to suffix it by sso 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:

但是,如果您不想像在我的情况下那样更改名称,我正在使用inventorytable,所以我不想给它添加后缀,s所以我将在模型中提供表名 asprotected $table = 'Table_name_as_you_want'然后不需要更改表名

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.

您必须在模型中提供表名,否则它不会出错。

回答by Steven Grauwmans

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

你应该在你的 PostController 中更改/添加:(并将 PostsController 更改为 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

PS:使用 route() 意味着您已将您的路线命名为

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

UPDATE

更新

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

上面的评论也对,把你的“帖子”模型改成“帖子”