如何修复错误未找到基表或视图:1146表laravel关系表?

时间:2016-08-04 14:54:17

标签: laravel laravel-5 laravel-5.2

我是一个新的laravel我尝试在表之间创建多对多的关系,当我将数据插入数据库时​​出现问题我遇到了错误

Connection.php第713行中的QueryException:SQLSTATE [42S02]:未找到基表或视图:1146表' learn.category_posts'不存在(SQL:插入category_postscategory_idposts_id)值(4,))

任何人都可以帮助我。以下是我的迁移和代码:

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

和我的模特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');
}

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

12 个答案:

答案 0 :(得分:5)

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

答案 1 :(得分:4)

Laravel尝试猜测表的名称,你必须直接指定它,以免它给你错误..

试试这个:

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

我希望有所帮助!

答案 2 :(得分:1)

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

答案 3 :(得分:1)

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

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

  

按照惯例,除非明确指定其他名称,否则将使用“蛇格”(即类(模型)的复数名称)作为表名

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

php artisan make:model Test --migration

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

Test.php

2018_06_22_142912_create_tests_table.php

如果您查看这两个文件中的代码,

2018_06_22_142912_create_tests_table.php 文件的向上功能,

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

它在此处自动生成了代码,其表名为“ tests”,该表名是该类的复数名称,位于 Test.php 文件中。

答案 4 :(得分:0)

您应该在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:使用route()表示您已将路径命名为

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

<强>更新

上述评论也是正确的,请更改您的帖子&#39;模型到&#39;发布&#39;

答案 5 :(得分:0)

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

答案 6 :(得分:0)

您可以简单地解决此问题,将其添加到发布模型

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

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

答案 7 :(得分:0)

尝试在创建应用之前检查应用是否在使用表 例如appServiceProvider.php

您可能会在未创建表的情况下调用该表,如果要对其进行注释,然后运行php artisan migration。

答案 8 :(得分:0)

要解决基表或视图未找到的错误,您可以执行操作,就像@Alexey Mezenin所说的那样,将表名category_post更改为category_posts

但是,如果您不想更改名称(例如我的情况),我正在使用inventory表,因此我不想在s后缀它,因此我将提供表模型中的名称为protected $table = 'Table_name_as_you_want',则无需更改表名称:

更改您要在其中出错的模块的型号,例如:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

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

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

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

答案 9 :(得分:0)

由于拼写错误或数据库名称未定义而发生此问题。确保您的数据库名称,表名称和所有列名称与phpmyadmin中的相同

答案 10 :(得分:0)

如果您遇到此错误,但您的问题有所不同,并且您厌倦了长时间的搜索,那么这可能对您有所帮助。

如果您更改了数据库并更新了 .env 文件,但仍然面临同样的问题,那么您应该检查 C:\xampp\htdocs{your-project-name}\bootstrap\cache\config.php 文件并替换或删除旧的数据库名称和其他更改的项目。

答案 11 :(得分:0)

只需运行命令:

import numpy as np
import matplotlib.pyplot as plt
 

barWidth = 0.25
fig = plt.subplots(figsize =(12, 8))
 

world_rank_x = [2, 2, 2, 2, 2]
world_rank_y = [6, 6, 6, 6, 6]

 
br1 = np.arange(len(world_rank_x))
br2 = [x + barWidth for x in br1]
 
plt.bar(br1, world_rank_x, color ='r', width = barWidth,
        edgecolor ='grey', label ='world_rank_x')
plt.bar(br2, world_rank_y, color ='g', width = barWidth,
        edgecolor ='grey', label ='world_rank_y')

 
plt.xlabel('Year', fontweight ='bold', fontsize = 15)
plt.ylabel('world rank', fontweight ='bold', fontsize = 15)
plt.xticks([r+(barWidth)/2 for r in range(len(world_rank_x))],
        ['2015', '2016', '2017', '2018', '2019'])
 
plt.legend()
plt.show()