D
D
Donald_Duck2018-07-03 12:36:14
MySQL
Donald_Duck, 2018-07-03 12:36:14

How to specify a foreign key to multiple tables?

Hello! There are several tables: posts, comments, messages, etc. And each has an associated table post_files, comment_files, and so on. But they are essentially identical, and so I decided to combine them into one by adding a field with the type (post, message, ...,) and a common field that will connect (relationship_id). I just can't figure out how to make the foreign key work.
How can this be specified in the context of Laravel? I know how to link with one table

$table->foreign('relationship_id')->references('id')->on('posts');

But how to connect with several?
Well, or if I’m not approaching the solution of the problem correctly, then I’ll be glad if you put me on the right path :)

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Alexander Aksentiev, 2018-07-03
@Donald_Duck

https://laravel.com/docs/5.6/eloquent-relationship...

A
Alexey Ukolov, 2018-07-03
@alexey-m-ukolov

how to make foreign key work
No, Mysql doesn't support it.

V
Vasily Nazarov, 2018-07-03
@vnaz

In the comments to one of the previous answers, they lied a little tangibly
->foreign () plays a role, and an essential one, because create FK at the DBMS level, which gives:
1. Integrity
2. Indexes
Another thing is that Laravel links can work without FK. That sometimes doesn't matter, and sometimes it doesn't.
And, if I remember correctly, when creating a link in Lara, indexes are not automatically created, then you will most likely need to create them explicitly.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question