Home > PHP Framework > Laravel > body text

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

藏色散人
Release: 2020-09-09 09:20:09
forward
2165 people have browsed it

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:<div class="code" style="position:relative; padding:0px; margin:0px;"><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><div class="contentsignin">Copy after login</div></div>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;);
Copy after login

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!

Related labels:
source:learnku.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!