我正在创建一个包含帖子/主题/类别的网站:
我希望这是有道理的,对此最好的MYSQL结构是什么? 我也在使用Laravel,所以如果你能解释这个结构的雄辩关系,我将不胜感激。
答案 0 :(得分:1)
阅读一些Relational Database Design
以下是一个例子:“
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 documentation有关如何创建Laravel模型的信息。
答案 1 :(得分: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的标准,并减少混乱。