问题
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]: 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))
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'));
}
And here is my model:
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);
}
}
Category .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);
}
}
For abouts table
public function up()
{
Schema::create('abouts', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->text('body');
$table->timestamps();
});
}
For categories table
public function up()
{
Schema::create('categories', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestamps();
});
}
回答1:
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');
});
来源:https://stackoverflow.com/questions/54494782/base-table-or-view-not-found-1146-table-laravel-5-7