DrugReportAss.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. <?php
  2. namespace App\Models;
  3. use Illuminate\Database\Eloquent\Factories\HasFactory;
  4. use Illuminate\Database\Eloquent\Model;
  5. use Illuminate\Database\Eloquent\SoftDeletes;
  6. use Illuminate\Support\Carbon;
  7. use App\Models\DrugReportInfo;
  8. use Illuminate\Support\Facades\DB;
  9. use Illuminate\Support\Facades\Log;
  10. use Illuminate\Database\Eloquent\Relations\HasMany;
  11. class DrugReportAss extends Model
  12. {
  13. use HasFactory;
  14. protected $table = 'drug_report_ass';
  15. // 是否主动维护时间戳
  16. public $timestamps = false;
  17. protected $guarded = [];
  18. public function drug_report_info(): HasMany
  19. {
  20. return $this->hasMany(DrugReportInfo::class, 'drug_id', 'drug_id')
  21. ->where('drug_report_info.batch_no', 'drug_report_ass.batch_no');
  22. }
  23. /**
  24. * 批量更新或插入
  25. * @param array $data
  26. * @param array $uniqueKeys
  27. * @return int
  28. * @throws \Throwable
  29. */
  30. public static function bulkUpsert(array $data, array $uniqueKeys = ['batch_no', 'drug_id','bill_id','bill_detail_id']): int
  31. {
  32. if (empty($data)) {
  33. return 0;
  34. }
  35. return DB::transaction(function () use ($data, $uniqueKeys) {
  36. $count = 0;
  37. foreach (array_chunk($data, 100) as $chunk) {
  38. try{
  39. $res = DrugReportAss::query()->upsert(
  40. $chunk,
  41. $uniqueKeys, // 组合唯一键
  42. ['update_time'] // 要更新的字段
  43. );
  44. if (!$res){
  45. log::info('increment_drug_upsert:更新失败:'.$res);
  46. }
  47. } catch (\Exception $e) {
  48. log::info('increment_drug_upsert:'.$e->getMessage());
  49. return $count;
  50. }
  51. $count += count($chunk);
  52. }
  53. return $count;
  54. });
  55. }
  56. }