自动插入新评论时,如何在评论表引用中添加评论表引用的文章字段

时间:2019-04-26 17:44:38

标签: php laravel

我在表注释上有引用段问题。 我想从表格帖子中添加子弹帖子

因此,当我插入评论时,它可以将posttable中的commentable_slug放入。这是我的评论表和帖子表。 commentable_id = 32,表示post_id,您可以从帖子中看到弹头,即(quia-pariatur-expedita-vel-quia)

评论表 enter image description here

后桌 enter image description here

和我的迁移

Schema::create('comments', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('user_id')->unsigned();
        $table->integer('parent_id')->unsigned()->nullable();
        $table->text('body');
        $table->integer('commentable_id')->unsigned();
        $table->foreign('commentable_id')->references('id')->on('posts')->onDelete('cascade');
        $table->string('commentable_slug')->nullable();
        $table->foreign('commentable_slug')->references('slug')->on('posts')->onDelete('cascade');
        $table->string('commentable_type');
        $table->timestamps();
    });

我在commentable_slug中使用null,因为它总是警告我无法添加或更新子行:外键约束失败

当我尝试我的可注释字段为空时。

我的评论模型和关系

 class Comment extends Model
{
    public function user()
    {
        return $this->belongsTo(Member::class);
    }
    public function post()
    {
        return $this->belongsTo(Post::class);
    }
    public function replies()
    {
        return $this->hasMany(Comment::class, 'parent_id');
    }
}

和我的帖子模型

    class Post extends Model
    {
     public function user()
    {
        return $this->belongsTo(User::class);
    }
    public function comments()
        {
            return $this->morphMany(Comment::class, 'commentable')->whereNull('parent_id');
        }
    }

部分代码错误的地方? 预期结果必须是: enter image description here

如何解决我的问题?

1 个答案:

答案 0 :(得分:1)

好吧,我想我了解您要做什么。问题在这里

public function post()
{
    return $this->belongsTo(Post::class);
}

由于它具有多态关系,因此您不能使用标准的belongsTo,因为您的表中没有post_id

您需要在评论模型中使用类似morphTo的功能

public function commentable()
{
    return $this->morphTo();
}

因此,当您致电

$comment->commentable()->get();

然后它将返回链接的任何多态模型。

由于您还没有给出任何用例,因此很难给出精确的代码示例。

但是,正如评论中所说,您不需要同时链接id和slug。另外,我相信MySQL在使用文本字段作为键时会遇到问题,我认为您需要指定字段长度,但不能指定100%的长度,也许对MySQL有更多了解的人可以确认这一点。

相关问题