找不到基本表或视图:1146表Laravel 5.7 [英] Base table or view not found: 1146 Table Laravel 5.7
问题描述
当我尝试使用Laravel 5将数据保存到mysql时,出现了此错误,其他形式和save()方法都可以正常工作,但这是这样的:
Im getting this error when I try to save data to mysql using Laravel 5, other forms and save() methods work fine but this one:
SQLSTATE [42S02]:未找到基表或视图:1146表'datatest.about_category'不存在(SQL:插入
about_category
(about_id
,category_id
)值(11,4))
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'datatest.about_category' doesn't exist (SQL: insert into
about_category
(about_id
,category_id
) values (11, 4))
这是我的Controller存储方法:
Here is my Controller store method:
public function store(AboutRequest $request)
{
$about = new About();
$about->title = $request->title;
$about->body = $request->body;
$about->save();
$about->categories()->attach(request('category'));
return redirect(route('abouts.create'));
}
这是我的模特:
About.php
About.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class About extends Model
{
public $table = "abouts";
public function categories()
{
return $this->belongsToMany(Category::class);
}
}
类别.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
protected $table = "categories";
public $fillable = ['id' , 'name'];
public function abouts(){
return $this->belongsToMany(About::class);
}
}
关于Abouts表
public function up()
{
Schema::create('abouts', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->text('body');
$table->timestamps();
});
}
对于类别表
public function up()
{
Schema::create('categories', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestamps();
});
}
推荐答案
您的多对多关系需要三个表:abouts
,categories
和about_category
.您尚未创建about_category
表:
Your many-to-many relationship requires three tables: abouts
, categories
, and about_category
. You haven't created the about_category
table:
Schema::create('about_category', function (Blueprint $table) {
$table->integer('about_id')->unsigned();
$table->integer('category_id')->unsigned();
$table->foreign('about_id')->references('id')->on('abouts');
$table->foreign('category_id')->references('id')->on('categories');
});
这篇关于找不到基本表或视图:1146表Laravel 5.7的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!