【问题标题】:Laravel 5.1 HasMany Relationship IssueLaravel 5.1 HasMany 关系问题
【发布时间】:2015-11-30 05:05:07
【问题描述】:

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

数据库中的表

  1. 帖子

    • post_id
    • post_detail
  2. cmets

    • comment_id
    • post_id
    • 评论
  3. 喜欢

    • like_id
    • comment_id

【问题讨论】:

  • 发帖不能点赞?
  • 是的,通常帖子有喜欢而不是 cmets。这只是关系的详细说明,那么我该如何定义这种类型的关系呢?并且与多个表有很多关系?

标签: php laravel-5.1


【解决方案1】:

我认为可以通过几种方式做到这一点。我已经按照以下方式实现了为 1.post-comment 2.comment-like 保留两个数据透视表。然而,这种方式可能不是最好的方式,但它确实有效。我的桌子看起来像......

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 类和所有其他代码才能正常工作。这只是数据库迁移部分。

【讨论】:

    猜你喜欢
    • 2014-04-18
    • 2019-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-28
    • 2018-03-14
    • 1970-01-01
    • 2017-05-18
    相关资源
    最近更新 更多