【问题标题】:Linking a Model (ie. comment) to many other Models (ie. post, profile)将模型(即评论)链接到许多其他模型(即帖子、个人资料)
【发布时间】:2015-03-03 14:16:19
【问题描述】:

我正在使用 Laravel 构建一个 PHP 应用程序,其中我有一个 Comment 模型和许多其他可以附加 Comment 的模型。

例如,Profile 可以有多个Comment,但Post 可以有多个Comment

我应该将Comment 分成两个模型(ProfileCommentPostComment)还是应该像这样将它们放在一起?

class Comment {

    public function user()
    {
        return $this->hasOne('User');
    }

    public function profile()
    {
        return $this->belongsTo('Profile');
    }

    public function post()
    {
        return $this->belongsTo('Post');
    }

}

如果我将它们放在一起,那么在数据库级别我应该如何管理comments 表?

我正在考虑拥有以下列:

integer: id - auto-incrementing id
integer: user_id - the user id
integer: foreign_id - profile/post id
varchar: type - which model? profile or post?
varchar: content - the actual comment

这是错误的方法吗?

【问题讨论】:

    标签: php database-design model-view-controller laravel-4 orm


    【解决方案1】:

    如果您想使用 1 个表格,您需要使 Comment 模型变形。 如果你不想使用变形,请分开。

    我认为如果您将使用问题中的架构,您将使用 morph。

    我不知道哪里需要制作更多的表,因为所有 cmets 将具有相同的结构(id、user_id(作者)、评论)

    所以在这种情况下,您只需使其变形(可标记)。

    【讨论】:

    • 那我的方法正确吗?因为不知何故我需要知道附加的评论是哪个模型。
    • 如果你使用Morph,你就不用担心“attached to”了,因为你会做这样的事情:Post::cmets() 或 Profile::cmets()。剩下的会做他。在数据库中,您将具有如下结构: id user_id comment commentable_id commentable_type
    • 我明白了,太好了。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2023-03-19
    • 2022-01-10
    • 1970-01-01
    • 1970-01-01
    • 2022-09-30
    • 1970-01-01
    • 2017-05-23
    • 1970-01-01
    相关资源
    最近更新 更多