close
Q: 如何在Laravel insert資料前先檢查此資料是否已存在DB中?
A: 先使用where條件加上count()去檢查資料是否存在。
若count>0代表存在,count==0代表不存在。
--
The Solution
$count = Assignment::where('asset_id', '=' ,$assignments->asset_id)->
where('status', '=' ,'Active')->
count();
if($count == 1 && $assignments->status != 'Disable') {
abort(405, 'Trying to assign an already assigned asset');
}
The mistake in my code: I was counting all Assignments and if there is any active status i got an error....I needed to check exactly that assignment which i want to assign which was either active or disable then the assignment should occur or not pertaining it's status(active/disable). Thanks Y'all esp apokryfos.
--
轉自 https://stackoverflow.com/questions/47710470/laravel-check-if-record-exists-before-insertion
--
全站熱搜
留言列表