简体   繁体   English

Laravel 5.2中标记系统的数据库关系

[英]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... 所以我想要一个标记表来处理所有这些标记,但是出于我的远见并坚持Laravel的约定,以便我可以利用关系方法,我必须对flags表做类似的事情...


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! 我不喜欢这种凌乱的解决方案,我也想不出另一种Laravel-y的方法!


I need to figure out a scalable way to handle flags with one table for multiple things in a Laravel 5.2 way. 我需要找出一种可扩展的方式,以Laravel 5.2的方式用一个表处理多个事物的标志。

You should take a look at polymorphic relations: https://laravel.com/docs/master/eloquent-relationships#many-to-many-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 . 您创建一个flags表和一个名为flaggable的表。 Flaggable has the columns id , flag_id , flaggable_type , and flaggable_id . Flaggable具有idflag_idflaggable_typeflaggable_id Then an entry might be 那么一个条目可能是

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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