Home  >  Article  >  PHP Framework  >  How to use constrained method to set database foreign key in Laravel7

How to use constrained method to set database foreign key in Laravel7

藏色散人
藏色散人forward
2020-09-09 09:20:092074browse

The following tutorial column will introduce you to How to use constrained method to set database foreign key in Laravel7 7 using the constrained method to set database foreign keys. I hope it will be helpful to friends in need!

Hi everyone,

How to use constrained method to set database foreign key in Laravel7Today, I wanted to write a quick tip about using foreign keys in How to use constrained method to set database foreign key in Laravel77.

This approach will help you write shorter migrations and make the code more readable.

In our example I'm using the very common

user_id

which can be applied to any foreign key.

Before, we would write like this:

$table->unsignedBigInteger('user_id')
->index();

$table->foreign('user_id')
->references('id')
->on('users')
->onDelete('cascade');
Well, that’s a bit lengthy, right?

The good news is that we can now write:

$table->foreignId('user_id')
->index()
->constrained()
->onDelete('cascade');

It’s more concise and easier to read. I hope you like this tip.

If you find it useful, please share it with your friends.

Have a nice day.

Original address: https://dev.to/wolfiton/laravel-7-short-cuts-to-writing-foreign-keys-4c1o

Translation address: https: //learnku.com/laravel/t/49371

The above is the detailed content of How to use constrained method to set database foreign key in Laravel7. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:learnku.com. If there is any infringement, please contact admin@php.cn delete