【发布时间】:2020-07-28 22:40:05
【问题描述】:
我有两个具有多对多关系的模型,我确实将它们与具有第三个表的模型连接起来。
将虚拟数据插入第三张表而不会出现 sql 错误以打破有关外键小鸡的约束的最佳方法是什么? 有没有办法使用前两个表中已经存在的相同数据?
我有这两张表:
class CreateLessonsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('Lessons', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('user_id');
$table->string('title', 100);
$table->text('body');
$table->timestamps();
$table->foreign('user_id')
->references('id')
->on('users')
->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('Lessons');
}
}
第二个:
class CreateTagsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('tags', function (Blueprint $table) {
$table->id();
$table->string('name', 50);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('tags');
}
}
和“加入”第三张表:
class CreateLessonTagsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('lesson_tags', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('lesson_id');
$table->unsignedBigInteger('tag_id');
$table->foreign('lesson_id')->references('id')->on('lessons')->onDelete('cascade');
$table->foreign('tag_id')->references('id')->on('tags')->onDelete('cascade');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('lesson_tags');
}
}
提前致谢
【问题讨论】:
-
澄清一下 - 你有 set up the many-to-many relationships?
标签: mysql database laravel dummy-data