0

我正在创建一个包含帖子/主题/类别的网站:

  • 一篇文章可以属于多个主题
  • 一个主题可以属于多个类别
  • 当然,一个Category有很多Topics和很多Posts,一个Topic有很多Posts

我希望这是有道理的,最好的 MYSQL 结构是什么?我也在使用 Laravel,所以如果你能解释这个结构的 Eloquent 关系,那将不胜感激。

4

2 回答 2

1

阅读一些关系数据库设计

这是一个例子:”

Categories table
Id
Name
...

Topics table
Id
Name
...

Posts table
Id
Name
...

Category_Topic Table
category_id    
topic_id

Topic_Post Table
topic_id
post_id

阅读Laravel : Eloquent 文档,了解如何创建 Laravel 模型。

于 2013-10-24T14:35:37.103 回答
0
// Migrations
Schema::create('categorys', function($table)
{
    $table->increments('id');
    $table->string('name');
    $table->string('description;);
    $table->timestamps();
});

Schema::create('topics', function($table)
{
    $table->increments('id');
    $table->integer('category_id');
    $table->string('name');
    $table->string('description');
    $table->timestamps();
});

Schema::create('posts', function($table)
{
    $table->increments('id');
    $table->string('imageable_type');
    $table->integer('imageable_id');
    $table->text('content');
            $table->timestamps();
})

// Models
class Category extends Eloquent {

    public function topics()
    {
        return $this->hasMany('Topic');
    }

    public function posts()
    {
        return $this->morphMany('Post', 'imageable');
    }

}

class Topic extends Eloquent {

    public function category()
    {
        return $this->belongsTo('Category');
    }

    public function posts()
    {
        return $this->morphMany('Post', 'imageable');
    }
}

class Post extends Eloquent {

    public function imageable()
    {
        return $this->morphTo();
    }
}


// Very simple controller example which walks through the relationships and echos the content.
class ConversationController extends BaseController {

    public function conversations()
    {
        $categories = Category::all();
        foreach($categories as $category)
        {
            foreach($category->topics as $topic)
            {
                foreach($topic->posts as $post)
                {
                    echo $category->name;
                    echo $topic->name;
                    echo $post->content;
                }
            }
        }

    }
}

我故意拼错categorys是为了更好地符合 Laravel 的标准并减少混乱。

于 2013-10-24T15:15:34.550 回答