Home >PHP Framework >Laravel >How to use constrained method to set database foreign key in Laravel7
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,Today, 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_idwhich can be applied to any foreign key.
Before, we would write like this:<pre class="brush:php;toolbar:false;">$table->unsignedBigInteger(&#39;user_id&#39;)
->index();
$table->foreign(&#39;user_id&#39;)
->references(&#39;id&#39;)
->on(&#39;users&#39;)
->onDelete(&#39;cascade&#39;);</pre>
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-4c1oTranslation address: https: //learnku.com/laravel/t/49371The 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!