Brightside
Brightside

Reputation: 131

DB many to many for more than one table?

I have posts table and content table and both of them have tags and in order to connect them I think I should use many-to-many relational table (that will store each id's).

But I wonder if I need to do it for every new table/content that will associate with the tags table?

So in this case I should have 2 relational tables:

post_tag
-> post_id
-> tag_id

content_tag
-> content_id
-> tag_id

right?
so if ill have another table, lets say videos then I'll have another relational table?
video_tag
-> video_id
-> tag_id

And since I work with laravel 4, belongTo and hasMany take care of the queries right?

Upvotes: 0

Views: 59

Answers (2)

Jacob Ball
Jacob Ball

Reputation: 1

You could look into Many to Many Polymorphic Relations (http://laravel.com/docs/eloquent#many-to-many-polymorphic-relations), as a Tag could belong to either a Post, Content or Video model. In fact, the example on the Laravel docs site is very similar to what you propose.

Upvotes: 0

Michael Green
Michael Green

Reputation: 1491

It is best practice to have separate association tables for each usage. The alternative - to have all the intersections in one table with a flag to distinguish them, will eventually give deeper indexes with more expensive lookups to give but one practical reason. From a theory point of view you have muddied the primary key with made up values.

Upvotes: 1

Related Questions