Laravel :: 更新外键的最佳方式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38427672/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel :: Best way to update a foreign key
提问by Yevgeniy Afanasyev
I have this migration file
我有这个迁移文件
Schema::create('table_one', function(Blueprint $table)
{
$table->increments('id');
$table->string('name');
$table->integer('table_two_id')->unsigned();
$table->foreign('table_two_id')->references('id')->on('table_two');
$table->timestamps();
});
and I want to update to make it ->onDelete('cascade');
我想更新以使其成为->onDelete('cascade');
$table->foreign('table_two_id')->references('id')->on('table_two')->onDelete('cascade');
What is the best way to do this?
做这个的最好方式是什么?
Is there something like ->change();
有没有像->change();
Thanks
谢谢
回答by Borut Flis
Drop the foreign key then add it again and run migrate.
删除外键,然后再次添加并运行迁移。
public function up()
{
Schema::table('table_one', function (Blueprint $table) {
$table->dropForeign(['table_two_id']);
$table->foreign('table_two_id')
->references('id')
->on('table_two')
->onDelete('cascade');
});
}
回答by Ricard
Christopher K. is right, at the Laravel docs says:
Christopher K. 是对的,在 Laravel 文档中说:
To drop a foreign key, you may use the dropForeign method. Foreign key constraints use the same naming convention as indexes. So, we will concatenate the table name and the columns in the constraint then suffix the name with "_foreign":
要删除外键,您可以使用 dropForeign 方法。外键约束使用与索引相同的命名约定。因此,我们将连接表名和约束中的列,然后在名称后缀“_foreign”:
$table->dropForeign('posts_user_id_foreign');
Or, you may pass an arrayvalue which will automatically use the conventional constraint name when dropping:
或者,您可以传递一个数组值,该值将在删除时自动使用常规约束名称:
$table->dropForeign(['user_id']);
https://laravel.com/docs/5.7/migrations#foreign-key-constraints
https://laravel.com/docs/5.7/migrations#foreign-key-constraints
回答by Ajmal Sarim
How to do via Controller
如何通过控制器进行
1- Set a Rought:
Route::get('foreignkeyforimg', "foreignkey@index");
2- Create controller With Foreignkey Name.
3- Foreignkey Controller with extend from Migration class.
4- Go to database and delete old primary key manually from the table
1- 设置一个 Rought:
Route::get('foreignkeyforimg', "foreignkey@index"); 2- 使用外键名称创建控制器。
3- 外键控制器从迁移类扩展。
4-转到数据库并从表中手动删除旧的主键
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
class Foreignkey extends Migration
{
function index(){
Schema::table('images', function (Blueprint $table) {
$table->foreign('sub_cat_id')
->references('id')
->on('subcategories')
->onDelete('cascade');
});
}
}