数据库设计:cms的菜单表

时间:2016-12-20 16:06:44

标签: php mysql laravel database-design

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

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

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

我应该添加一个名为menu_type的列来定义菜单类型,该列可以包含以下值:url,category或content。是否必须创建另一个这样的表:

id | TYPE_NAME

1 |类别

2 |内容

3 | URL

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

非常感谢。

1 个答案:

答案 0 :(得分:0)

根据您的要求,您可以在categoriescontents和{}之间建立M-M Polymorphic Relationshipsmenus

您的表格结构应为:

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_id&amp; owner_type字段为空,或者您可以定义一个额外的列type来定义菜单类型。

希望这有帮助!

相关问题