简体   繁体   中英

Database relationships for a flagging system in Laravel 5.2

Problem

I'm building an application where are many things a user can flag. Lets take these example things a user can flag:

  • Another user
  • An image
  • A comment
  • A tag

So I want one flagging table to deal with flagging all these things, but with my vision and to stick to Laravel's conventions so I can make use of relationship methods, I'd have to do something like this for the flags table...


My "solution"

+----+---------+----------+--------+------------+-----------------------------+
| id | user_id | image_id | tag_id | comment_id | message                     |
+----+---------+----------+--------+------------+-----------------------------+
| 1  | 3       | null     | null   | null       | I'm building an application |
+----+---------+----------+--------+------------+-----------------------------+
| 2  | null    | 45       | null   | null       | This image is NSFW!         |
+----+---------+----------+--------+------------+-----------------------------+
| 3  | null    | null     | 234    | null       | Tag includes bad content... |
+----+---------+----------+--------+------------+-----------------------------+
| 4  | null    | null     | null   | 125        | Spamming!!!                 |
+----+---------+----------+--------+------------+-----------------------------+

Now this way, this flagging system is not scalable at all! If I want to be able to flag things in the future, I'd have to add a column and map it etc.

I don't like this messy solution and I can't think of another Laravel-y way to do this!


I need to figure out a scalable way to handle flags with one table for multiple things in a Laravel 5.2 way.

You should take a look at polymorphic relations: https://laravel.com/docs/master/eloquent-relationships#many-to-many-polymorphic-relations

You create a table for flags and a table called flaggable . Flaggable has the columns id , flag_id , flaggable_type , and flaggable_id . Then an entry might be

1 | 1 (id of the flag) | App\\Image (type of flaggable) | 45 (ID of image)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM