Laravel 防止数据库中的数据重复
Laravel prevent data duplicate in database
我想防止用户多次申请工作时数据库中的数据重复post。
我试过firstOrNew()
喜欢...
$apply = Applies::firstOrNew(
['user_id' => Auth::id()],
['posts_id' => request('id')]);
$apply->save();
但是这次用户不能再申请其他 post 了。
编辑 1
我试过了,但什么也没做。
$apply = Applies::firstOrNew(
['user_id' => Auth::id()] && ['posts_id' => request('id')],
['user_id' => request(Auth::id())],
['posts_id' => request('id')]);
$apply->save();
第一个数组是“属性”,查找的where条件。您需要在该数组中包含 user_id
和 post_id
:
Applies::firstOrNew([
'user_id' => ...,
'post_id' => ...,
]);
这将导致它搜索该组合,只有在找不到时才会创建一个新的(不存在的)模型实例并用这些“属性”填充它。
我想防止用户多次申请工作时数据库中的数据重复post。
我试过firstOrNew()
喜欢...
$apply = Applies::firstOrNew(
['user_id' => Auth::id()],
['posts_id' => request('id')]);
$apply->save();
但是这次用户不能再申请其他 post 了。
编辑 1 我试过了,但什么也没做。
$apply = Applies::firstOrNew(
['user_id' => Auth::id()] && ['posts_id' => request('id')],
['user_id' => request(Auth::id())],
['posts_id' => request('id')]);
$apply->save();
第一个数组是“属性”,查找的where条件。您需要在该数组中包含 user_id
和 post_id
:
Applies::firstOrNew([
'user_id' => ...,
'post_id' => ...,
]);
这将导致它搜索该组合,只有在找不到时才会创建一个新的(不存在的)模型实例并用这些“属性”填充它。