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

我在表注释上遇到了参考子弹的问题。我想从表格帖子中添加子弹帖子。

所以当我插入评论时,它可以将posttable中的commentable_slug放进去。这是我的评论表和帖子表。commentable_id = 32,这意味着post_id,您可以从post中看到该文件,即(quia-pariatur-expedita-vel-quia)

评论表

http://img1.mukewang.com/60a716700001f25712420110.jpg

发布表

http://img2.mukewang.com/60a7167f0001ace712100206.jpg

和我的迁移


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,因为它总是警告我无法添加或更新子行:外键约束失败。


当我尝试我的字段comableable为null时。

如何解决我的问题?


慕工程0101907
浏览 119回答 1
1回答

Qyouu

好的,我想我了解您正在尝试做的事情。问题在这里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有更多了解的人可以确认这一点。
打开App,查看更多内容
随时随地看视频慕课网APP