Ligonsker's avatar

Should I use hasMany or belongsToMany in this case?

I need to store user uploaded files.

I have 3 tables: users, folders and files

The folders aren't actual filesystem folder, but a folder the user creates on the app and then can put files there.

I was thinking to do the following relationships:

  • user has many files and has many folders
  • folders belong to user and has many files
  • files belong to user and belong to a folder

But then I was thinking maybe I need to have belongsToMany between the folders and files - in case a user wants to "copy" a file to 2 folders (so view the file in both) - so I will add a pivot table folders_files.

But also I thought to add belongsToMany between the files and the users - so in case I want to add feature to "share" between the users and allow others to view files of other users.

So I still want to store the original uploader user_id in the files table - because it belongs to him because he uploaded it, but also have a pivot table for the sharing feature - is it a good design? Or I need to do it differently?

I can do the same with the folders and users (i.e. have folders_users with belongsToMany for the same purposes)

0 likes
2 replies
jlrdw's avatar

@ligonsker you said:

The folders aren't actual filesystem folder

So you are storing all of these images in the database instead of storage? That is really not efficient.

But just suggestion to store the files in a folder and not in a table.

Also I am trying to understand what you are doing. All you need is a folder for a user that only that user has access to and in that folder store the images and thumbnails for that user.

You can have a relation set up to determine what other users has access to, and just example: billybob_127.

In the above billybob_127 is Billy Bob's folder.

1 like
Ligonsker's avatar

@jlrdw I am storing the images in the filesystem, the files table only stores the path of the file

the folders are the name of the virtual folder (not real filesystem folder) - but a user creates a folder in his gallery and wants to move files there

Also I am not storing the files per user, I am storing per hash: If the hash name is d6199909d0b5fdc22c9db625e4edf0d6da2b113b21878cde19e96f4afe69e714.jpg, I will store it in /files/d/6/1//9/9/d6199909d0b5fdc22c9db625e4edf0d6da2b113b21878cde19e96f4afe69e714.jpg

Please or to participate in this conversation.