我有两张这样的表
图书
id|book_name|writter_id
1|Artemis|1
再考
id|writter_name
1|Jane Doe
这两个表都有这样的关系
预订模型 return $this->belongsTo('App\Writter', 'writter_id');
撰稿人模型 return $this->hasMany('App\Book', 'writter_id');
books.index.blade.php
<p>{{ $book->writter->writter_name }}</p>
创建图书
public function up()
{
Schema::create('books', function (Blueprint $table) {
$table->increments('id');
$table->string('book_name', 100)->unique();
$table->integer('writter_id')->unsigned();
$table->timestamps();
});
}
创建写作者
public function up()
{
Schema::create('writters', function (Blueprint $table) {
$table->increments('id');
$table->string('writter_name', 100);
$table->timestamps();
});
// Set Foreign Key
Schema::table('books', function (Blueprint $table) {
$table->foreign('writter_id')
->references('id')
->on('writers')
->onDelete('cascade')
->onUpdate('cascade');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
// Drop Foreign Key di kolom id_penulis di table books
Schema::table('books', function(Blueprint $table) {
$table->dropForeign('books_writter_id_foreign');
});
Schema::drop('writters');
}
每当我删除这些文字时(例如上面的jane doe),图书数据仍然有writter_id
所以索引视图会给我一个错误。
是否可以从 writters 表中删除数据/行,并同时删除图书上的writter_id
?
答案 0 :(得分:0)
编辑图书表格迁移并添加外键
$table->integer('writter_id')->unsigned()->nullable();
Schema::table('books', function($table) {
$table->foreign('writter_id')->references('id')->on('writters')->onDelete('set null');
});
如您所见,它在writter delete
上设置为null答案 1 :(得分:0)
对于make youre migration file,你使用外键吗? 使用外键,您可以为删除添加方法。
migration.php
doHighlight
它会起作用
答案 2 :(得分:0)
如果您还没有在表上设置外键,则从表中删除一行不会更新引用该行的列。
要解决此问题,我们可以使用架构构建器设置foreign keys。
如果您不关心当前的数据库值,则可以创建新的迁移文件或修改现有的迁移。
使用php artisan make:migration
创建新的迁移文件。在该文件中,使用这些方法(在运行迁移之前不要忘记运行composer require doctrine/dbal
):
public function up() {
// Remove current foreign keys and index.
Schema::table('books', function (Blueprint $table) {
$table->dropForeign('books_writter_id_foreign');
$table->dropIndex('books_writter_id_foreign');
});
// Add new foreign and allow books to now have a writter by using `NULL`.
Schema::table('books', function (Blueprint $table) {
$table->integer('writter_id')->unsigned()->nullable()->change(); // Before changing a column, be sure to add the doctrine/dbal dependency to your composer.json file.
$table->foreign('writter_id')
->references('id')
->on('writers')
->onDelete('SET NULL');
});
}
public function down() {
// Revert to previous values.
Schema::table('books', function (Blueprint $table) {
$table->dropForeign('books_writter_id_foreign');
$table->dropIndex('books_writter_id_foreign');
$table->integer('writter_id')->unsigned()->change();
$table->foreign('writter_id')
->references('id')
->on('writers')
->onDelete('cascade')
->onUpdate('cascade');
});
}
当从引用的表中删除引用的值时,在外键上使用->onDelete('SET NULL')
会将值设置为NULL
。
在您的刀片文件中,您现在可以在输出之前检查该书是否有作家:
@if ($book->writter_id)
<p>{{ $book->writter->writter_name }}</p>
@endif