I don't know how the WP library is built, but with open source you can take a look.
Regarding the structure of the table, assuming you need a many-to-many link, you need a cross-reference table, for example:
record_id (int) media_id (int) title (text) caption (text) rank (int)
Then the media table will look something like this:
id (int) title (text) caption (text) filename (text) type (image|multimedia|document)
Perhaps you would also add the folder_id field to the media table, or you might want to mark it instead, in which case you have a third table with media_id and a tag in the form of fields (or you have tags as values ββseparated by a comma in the media table).
This will allow you to associate one media with multiple items and one item with multiple media. This will allow you to set the title and caption for the media item and override it for a specific link. For example, you have a photograph of a house with an inscription whose house it is, but in one link the inscription is written (in the crosstab), with text saying how this house is an example of a certain architecture. The SQL coalesce function is useful for getting the correct name and title.
If the content that refers to the medium comes from several tables, let's say that you have a table called "state" and the other is called "products" and they can link to the medium, then the table_name field should also be in the cross-reference table The type field is that you can easily get only multimedia files attached to a recording, or just images; you can calculate how many documents are attached, how many images, etc., based on this file name for each request, it means that you have slower requests.
One thing that is not entirely satisfying is the placement of media outside the site. If you use "Amazon S3" to store these images, the "filename" field will actually be the URL for the image. I just shoot it there as something to consider when developing a media library.
I canβt come up with any literature or code that you can copy-paste, but this is not difficult to do, although I understand that it can take a lot of time.
Good luck.