gpt4 book ai didi

Laravel ManyToMany 关系正在反转表名称

转载 作者:行者123 更新时间:2023-12-04 08:27:13 26 4
gpt4 key购买 nike

我需要让帖子接受我需要的尽可能多的语言,所以我有两个模型 postlanguage在后模型中:

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();
});
在我的 Controller 中:
$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))
所以问题是由于某种原因表名被交换了!

最佳答案

基于模型的数据透视表的 Laravel 约定是 table1_table2 ,其中 table1是字母表中排在第一位的模型的小写单数版本,和 table2是字母表中最后一个模型的小写单数版本。所以在你的情况下,pivot表应该是 language_post ,因为 L 在 P 之前。
您可以在迁移中修改数据透视表:

Schema::create('language_post', ...)
或者在关系上覆盖它: Post.php :
public function languages() {
return $this->belongsToMany(Language::class, 'post_language');
}
Language.php
public function posts() {
return $this->belongsToMany(Post::class, 'post_language');
}
第二个参数传递给 belongsToMany是数据透视表的名称。
从文档:

To determine the table name of the relationship's intermediate table, Eloquent will join the two related model names in alphabetical order.


https://laravel.com/docs/8.x/eloquent-relationships#many-to-many

关于Laravel ManyToMany 关系正在反转表名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65202886/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com