简体   繁体   English

Laravel 5.1 HasMany关系问题

[英]Laravel 5.1 HasMany Relationship Issue

I have 3 tables posts, comments and likes. 我有3个表格的帖子,评论和顶。 One post can have multiple comments and one comments can have multiple likes. 一个帖子可以有多个评论,一个评论可以有多个赞。 How can I define relationship between 3 tables to fetch all posts details, including comments and likes of particular post_id in laravel 5.1? 如何定义3个表之间的关系以获取所有帖子详细信息,包括laravel 5.1中特定post_id的评论和喜欢?

Tables in DB 数据库中的表

  1. posts 帖子

    • post_id post_id
    • post_detail post_detail
  2. comments 评论

    • comment_id comment_id
    • post_id post_id
    • comment 评论
  3. likes 喜欢

    • like_id like_id
    • comment_id comment_id

I think this can be done is several ways. 我认为可以通过几种方法来完成。 I have implemented in following way keeping two pivot table for 1. post-comment 2. comment-like. 我已经按照以下方式实现了,以便为1.注释后2.注释式保留两个数据透视表。 However this way may not be the best way, but it works. 但是,此方法可能不是最佳方法,但它可以工作。 My tables looks like... 我的桌子看起来像...

1) comment table. 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) like table. 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"));
        });
    }

NOTE you need to add the Model class and all other codes required to make this work porperly. 注意,您需要添加Model类和使此工作更繁琐所需的所有其他代码。 This is only the database migration part. 这只是数据库迁移的一部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM