@addison
To create a table with foreign keys in Laravel, you can use the Schema
facade provided by Laravel's database migration feature. Here's an example of how you can create a table with foreign keys in a migration file:
1
|
php artisan make:migration create_posts_table |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
use IlluminateSupportFacadesSchema; use IlluminateDatabaseSchemaBlueprint; use IlluminateDatabaseMigrationsMigration; class CreatePostsTable extends Migration { public function up() { Schema::create('posts', function (Blueprint $table) { $table->increments('id'); $table->string('title'); $table->text('content'); $table->unsignedInteger('user_id'); $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade'); $table->timestamps(); }); } public function down() { Schema::dropIfExists('posts'); } } |
1
|
php artisan migrate |
This will create a posts
table with a foreign key constraint on the user_id
column referencing the id
column of the users
table.