【发布时间】:2018-06-10 17:44:50
【问题描述】:
我不想在我的 users 表中出现重复项。这样就好了:
╔═══╦════════════╦═════════════╦═════════════╗
║ ║ firstname ║ lastname ║ dateOfBirth ║
╠═══╬════════════╬═════════════╬═════════════╣
║ 1 ║ John ║ Mat ║ 1999-12-01 ║
║ 2 ║ Dave ║ Bittner ║ 1950-06-02 ║
║ 3 ║ John ║ Mat ║ 1900-11-02 ║
╚═══╩════════════╩═════════════╩═════════════╝
在我的 Laravel 应用程序 (UserController) 中,我通过调用 firstOrCreate 方法(创建新用户)检查用户是否已经存在:
public function store(UserRequest $request) {
$user = User::firstOrCreate([
'firstname' => request('firstname'),
'lastname' => request('lastname'),
'dateOfBirth' => request('dateOfBirth'),
]);
if($user->wasRecentlyCreated) {
// new
}else {
// existing
}
return redirect('/users');
}
这工作得很好。现在,我可以成功创建一个类似的用户(如上例表中带有id=3 的条目)。如果我将条目 3 中的生日编辑为 1999-12-01,Laravel 说没问题,但不是(与 id=1 重复)!
如果条目已经存在,我还想检查更新(每次更新后重复检查)。我正在搜索 updateIfNotDuplicate 方法或类似的方法(例如 firstOrCreate 以获取更新)。
这是我在UserController 中的update 函数:
public function update(User $user, UserRequest $request) {
$user->update([
'firstname' => request('firstname'),
'lastname' => request('lastname'),
'dateOfBirth' => request('dateOfBirth'),
]);
return redirect('/users');
}
【问题讨论】:
-
我认为使用 updateOrCreate() 可以解决您的问题
-
你有一个
UserRequest对象,为什么不在dateOfBirth列中添加一个unique约束? -
@Ohgodwhy:也有可能存在两个生日相同但名字不同的用户。我试图创建一个 MCVE。我真正的桌子要大得多。您可以将其视为孔表复合键(而不是 id 字段)。