Home >PHP Framework >Laravel >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:092267browse

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:<pre class="brush:php;toolbar:false;">$table-&gt;unsignedBigInteger(&amp;#39;user_id&amp;#39;) -&gt;index(); $table-&gt;foreign(&amp;#39;user_id&amp;#39;) -&gt;references(&amp;#39;id&amp;#39;) -&gt;on(&amp;#39;users&amp;#39;) -&gt;onDelete(&amp;#39;cascade&amp;#39;);</pre>Well, that’s a bit lengthy, right?

The good news is that we can now write:

$table->foreignId(&#39;user_id&#39;)
->index()
->constrained()
->onDelete(&#39;cascade&#39;);

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