- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个赞助应用程序,并尝试在用户赞助 child 后将赞助 child 和用户添加到数据透视表中。
我为赞助者 child 和用户创建了一个数据透视表。在第一个事务中,表中的关系是正确的,但如果用户返回并再次赞助 child 的第二个或第三个插槽,我会收到以下错误:
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '1-1' for key 'PRIMARY' (23000)
kid_user
数据透视表:
public function up()
{
Schema::create('kid_user', function (Blueprint $table) {
$table->integer('kid_id')->unsigned()->index();
$table->foreign('kid_id')->references('id')->on('kids')->onDelete('cascade');
$table->integer('user_id')->unsigned()->index();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->primary(['kid_id', 'user_id']);
$table->timestamps();
});
}
child 模特:
public function users() {
return $this->belongsToMany(User::class)->withTimestamps();
}
用户模型:
public function kids(){
return $this->belongsToMany(Kid::class)->withTimestamps();
}
使用此行连接到我的 Controller :
$cin = $request->cin;
$kidid = $request->kidid;
$kids = DB::table('kids')->where('cin', $cin)->increment('sponsors_received');
$user = Auth::user();
$user->kids()->attach($kidid);
//$user->kids()->sync($kidid);
;
我目前得到的:
+--------------------+
| kid_user table |
+--------------------+
| *kid_id | *user_id | * = Primary Key
+---------+----------+
| 1 | 1 | -> Sponsored 1st Slot
+---------+----------+
我想要得到什么:
+--------------------+
| kid_user table | THE BELOW RESULTS ARE WHAT I'M LOOKING FOR.
+--------------------+
| *kid_id | *user_id | * = Primary Key
+---------+----------+
| 1 | 1 | -> Sponsored 1st Slot (CURRENTLY GETTING)
+---------+----------+
| 1 | 1 | -> Sponsored 2nd Slot (ERRORS HERE!!!)
+---------+----------+
| 2 | 1 | -> Sponsored 3rd Slot (THIS WILL WORK)
+---------+----------+
我尝试在 Controller 中使用 sync
而不是 attach
,但 sync
只是覆盖第一个关系,而不是添加一个新关系表示用户正在赞助 child 的 3 个插槽中的第 1 个和第 2 个插槽。
还尝试在我的模型中使用 hasMany
关系,但这没有帮助。作为最后一次尝试,我还添加了创建/更新的列,希望能够使其独一无二,但没有运气..
最佳答案
问题出在数据库设计上。在您的表中,('kid_id','user_id') 集必须是唯一的。但是示例中的第二个 (1,1) 是错误的,因为已经存在一组 (1,1)。
如果您想让同一个用户多次赞助“同一个 child ”,那么您的方法将行不通。您可以使用不同的主键来维护此约束。在这种情况下,它应该类似于,
| pivot_id*| kid_id | user_id | * = Primary Key
+---------+---------+----------+
| 1 | 1 | 1 | -> Sponsored 1st Slot (CURRENTLY GETTING)
+---------+---------+----------+
| 2 | 1 | 1 | -> Sponsored 2nd Slot (SAME DATA WITH DIFFERENT KEY)
+---------+---------+----------+
| 3 | 2 | 1 | -> Sponsored 3rd Slot (THIS WILL WORK)
关于php - 如何修复完整性约束违规 : 1062 Duplicate entry '1-1' for key 'PRIMARY: Laravel Pivot Table,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54210731/
我是一名优秀的程序员,十分优秀!