我在表注释上遇到了参考子弹的问题。我想从表格帖子中添加子弹帖子。所以当我插入评论时,它可以将posttable中的commentable_slug放进去。这是我的评论表和帖子表。commentable_id = 32,这意味着post_id,您可以从post中看到该文件,即(quia-pariatur-expedita-vel-quia)评论表发布表和我的迁移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时。如何解决我的问题?
1 回答
![?](http://img1.sycdn.imooc.com/545868190001d52602200220-100-100.jpg)
Qyouu
TA贡献1786条经验 获得超11个赞
好的,我想我了解您正在尝试做的事情。问题在这里
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有更多了解的人可以确认这一点。
- 1 回答
- 0 关注
- 118 浏览
添加回答
举报
0/150
提交
取消