[英]Laravel 5.1 HasMany Relationship Issue
我有3个表格的帖子,评论和顶。 一个帖子可以有多个评论,一个评论可以有多个赞。 如何定义3个表之间的关系以获取所有帖子详细信息,包括laravel 5.1中特定post_id的评论和喜欢?
数据库中的表
帖子
评论
喜欢
我认为可以通过几种方法来完成。 我已经按照以下方式实现了,以便为1.注释后2.注释式保留两个数据透视表。 但是,此方法可能不是最佳方法,但它可以工作。 我的桌子看起来像...
1)评论表。
class PostCommentsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('post_comments', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('post_id');
$table->string('comment_owner_username');
$table->string('comment');
$table->timestamps();
});
}
2)喜欢桌子。
class CommentLikesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('comment_likes', function (Blueprint $table) {
$table->unsignedInteger('post_comment_id');
$table->unsignedInteger('user_id');
$table->timestamps();
$table->primary(array("post_comment_id", "user_id"));
});
}
注意,您需要添加Model
类和使此工作更繁琐所需的所有其他代码。 这只是数据库迁移的一部分。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.