在 Laravel 4 的 Eloquent 中,
我有一个表user和一个字段user.friend_id,它也是一个用户的 id..
但是当我尝试使用friend_id = 0创建一个新用户时,外键失败..
当friend_id = 1时,它成功。
我在用户的架构生成器中有这个
$table->unsignedInteger('friend_id')->default(0)->nullable();
我应该在这里做什么?
我应该刚刚创建了一个数据透视表吗?
谢谢!
您不应该为可以为空的外键设置默认值 0。
正确方法:
$table->unsignedInteger('friend_id')->nullable();
解释:
$table->unsignedInteger('friend_id')->default(0)->nullable();
当您尝试插入新记录时,请将friend_id 留空。
假设您可以有多个朋友,那么是的,您应该有一个数据透视表
用户表
id | name
1 | Laurence
2 | Ben
3 | Jane
Users_Friend 表
user_id | friend_id
1 | 2
1 | 3
这意味着劳伦斯是本和简的朋友