【问题标题】:Database design: menus table for a cms数据库设计:cms 的菜单表
【发布时间】:2017-05-05 22:04:24
【问题描述】:

我想为 cms 设计 menus 表。我已经有categoriescontents 表。菜单是指向特定类别或内容的链接,也可以是来自其他网站的 url。

如何定义每个菜单是一个类别还是一个内容? 我教过 category_idcontent_idurl 列都可以为空是很好的。

这是一个好方法吗?最好的方法是什么?

我是否应该添加一个名为menu_type 的列来定义菜单类型,它可以具有以下值:url、类别或内容。是否需要创建另一个这样的表:

标识 | type_name

1 |类别

2 |内容

3 |网址

并在 menu_type 列中为内容的类别 2 插入 1...作为外键?

非常感谢。

【问题讨论】:

  • 如果您没有任何与该类型特别相关的额外属性,您可以使用enum() 列。有了它,字符串“category”、“content”和“url”只存储一次,每个记录上都存储一个ID。但是,当您查询表时,MySQL 知道返回字符串而不是 ID。您也可以按字符串或 ID 进行搜索。所以WHERE type = 0WHERE type = 'category' 会返回相同的东西
  • 非常感谢。这是一个很好的解决方案!

标签: php mysql laravel database-design


【解决方案1】:

根据您的要求,您可以在categoriescontentsmenus之间构建一个M-M Polymorphic Relationships

你的表结构应该是:

categories
    id - integer
    name - string
    ...

contents
    id - integer
    name - string
    ...

menus
    id - integer
    body - text
    owner_id - integer
    owner_type - string
    ...

你的模型应该是这样的:

class Menu extends Model
{
    /**
     * Get all of the owning owner models.
     */
    public function owner() // <--------- Get the owner model object
    {
        return $this->morphTo();
    }
}

class Category extends Model
{
    /**
     * Get all of the post's owner.
     */
    public function menus() // <--------- Get all the associated Menu Model objects
    {
        return $this->morphMany('App\Menu', 'owner');
    }
}

class Content extends Model
{
    /**
     * Get all of the video's owner.
     */
    public function menus() // <--------- Get all the associated Menu Model objects
    {
        return $this->morphMany('App\Menu', 'owner');
    }
}

如果是url,您可以让owner_idowner_type 字段为空,或者您可以定义一个额外的列type 来定义菜单类型。

希望这会有所帮助!

【讨论】:

  • 谢谢!所以我想在一个列中存储像http://stackoverflow.com 这样的实际url 字符串,所以我必须有一个link 列?
  • 是的,您的菜单表中也可以包含该列!
猜你喜欢
  • 2012-10-07
  • 1970-01-01
  • 1970-01-01
  • 2013-02-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-18
  • 2012-02-19
相关资源
最近更新 更多