1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798 |
- <?php
- namespace App\Models;
- use Carbon\Carbon;
- use Dcat\Admin\Traits\HasDateTimeFormatter;
- use Illuminate\Database\Eloquent\Model;
- use Illuminate\Support\Facades\DB;
- class DistAppearanceTemplate extends Model
- {
- use HasDateTimeFormatter;
- protected $table = 'dist_appearance_template';
- /*
- * 把原始模板复制给分销商
- */
- public static function copyTemplateToDist($appearanceId,$distId) {
- $appearanceId = intval($appearanceId);
- $distId = intval($distId);
- $count = self::where('dist_id', $distId)->where('appearance_id', $appearanceId)->count();
- if ($count > 0) {
- return;
- }
- $baseDistId = config('dictionary.base_dist_id');
- //复制
- DB::statement("
- INSERT INTO `dist_appearance_template` (`dist_id`, `appearance_id`, `file_name`, `file_path`, `content`, `created_at`, `updated_at`, `template_code`)
- SELECT {$distId}, `appearance_id`, `file_name`, `file_path`, `content`, NOW(), NOW(), `template_code`
- FROM `dist_appearance_template`
- WHERE `dist_id` = {$baseDistId} AND `appearance_id` = {$appearanceId};
- ");
- }
- public static function deleteTemplates($appearanceId,$distId) {
- self::where('dist_id',$distId)->where('appearance_id',$appearanceId)->delete();
- return true;
- }
- public function syncAppearanceTemplates($appearanceId,$distId)
- {
- $appearanceId = intval($appearanceId);
- $distId = intval($distId);
- $criteria = ['dist_id' => $distId, 'appearance_id' => $appearanceId];
- $tmpModel = $this;
- $tempRecords = $tmpModel
- ->where($criteria)
- ->get();
- $siteModel = new SiteAppearanceTemplate();
- $siteRecords = $siteModel
- ->where($criteria)
- ->get()
- ->keyBy('id'); // Use IDs as keys for easier comparison
- foreach ($tempRecords as $tempRecord) {
- $siteRecord = $siteRecords->get($tempRecord->id);
- if ($siteRecord) {
- // If record exists in `site_appearance_template`, check for updates
- if ($tempRecord->updated_at > $siteRecord->updated_at) {
- $siteModel->where('id', $siteRecord->id)
- ->update([
- 'file_name' => $tempRecord->file_name,
- 'file_path' => $tempRecord->file_path,
- 'content' => $tempRecord->content,
- 'updated_at' => Carbon::now(),
- ]);
- }
- } else {
- // If record does not exist, insert it
- $siteModel->insert([
- 'id' => $tempRecord->id,
- 'dist_id' => $tempRecord->dist_id,
- 'appearance_id' => $tempRecord->appearance_id,
- 'file_name' => $tempRecord->file_name,
- 'file_path' => $tempRecord->file_path,
- 'content' => $tempRecord->content,
- 'created_at' => Carbon::now(),
- 'updated_at' => Carbon::now(),
- 'template_code' => $tempRecord->template_code,
- ]);
- }
- }
- // Delete records from `site_appearance_template` that don’t match `dist_id=1` and `appearance_id=1`
- $siteModel
- ->where($criteria)
- ->whereNotIn('id', $tempRecords->pluck('id')->toArray())
- ->delete();
- }
- }
|