Laravel 5.1有很多关系问题

时间:2015-11-30 05:05:07

标签: php laravel-5.1

我有3个表格帖子,评论和喜欢。 一个帖子可以有多个评论,一个评论可以有多个评论。如何定义3个表之间的关系以获取所有帖子的详细信息,包括laravel 5.1中特定post_id的评论和喜欢?

DB中的表

  1. 帖子

    • post_id
    • post_detail
  2. 评论

    • COMMENT_ID
    • POST_ID
    • 评论
  3. 喜欢

    • like_id
    • COMMENT_ID

1 个答案:

答案 0 :(得分:0)

我认为这可以通过几种方式完成。我已经按照以下方式实现了保留两个数据透视表,用于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类以及使此工作正常工作所需的所有其他代码。这只是数据库迁移部分。

相关问题