我需要让帖子接受尽可能多的语言,所以我有两个模型post
和 language
帖子模型:
public function languages(){
return $this->belongsToMany(\App\Models\Language::class);
}
在我的语言模型中:
public function posts()
{
return $this->belongsToMany(\App\Models\Post::class);
}
迁移后:
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->text('body');
$table->boolean('puplished')->default(false);
$table->bigInteger('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
$table->timestamps();
});
语言迁移:
Schema::create('languages', function (Blueprint $table) {
$table->id();
$table->string('text')->unique();
$table->string('value');
$table->timestamps();
});
我还创建了 post_language_table 迁移来连接帖子和语言:
Schema::create('post_language', function (Blueprint $table) {
$table->id();
$table->unsignedInteger('post_id');
$table->unsignedInteger('language_id');
$table->timestamps();
});
在我的控制器中:
$langs = collect(json_decode($request->languages,true))->pluck('id');
$post = [];
$post['body'] = $request->body;
$post['title'] = $request->title;
$post['user_id'] = 1;
$new_post = \App\Models\Post::create($post);
$new_post->languages()->attach($langs);
但是当我尝试将新记录插入到 tha 数据库时,此错误显示:
Illuminate\Database\QueryException
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'laravel.language_post' doesn't exist (SQL:
insert into `language_post` (`language_id`, `post_id`) values (1, 4), (3, 4), (4, 4))
所以问题是由于某种原因交换了表名!