林收到这个错误,当我尝试将数据保存到使用Laravel 5其他形式的MySQL,并保存()方法工作良好,但此一:
SQLSTATE [42S02]:基表或视图未找到:1146表 'datatest.about_category' 不存在(SQL:INSERT INTO
about_category
(about_id
,category_id
)的值(11,4))
这是我的Controller存储方法:
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
<?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();
});
}
答案 0 :(得分:0)
您的多对多关系需要三个表:abouts
,categories
和about_category
。您尚未创建about_category
表:
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');
});