clqms-be/app/Models/Location/LocationModel.php

87 lines
3.0 KiB
PHP

<?php
namespace App\Models\Location;
use App\Models\BaseModel;
class LocationModel extends BaseModel {
protected $table = 'location';
protected $primaryKey = 'LocationID';
protected $allowedFields = ['SiteID', 'LocCode', 'Parent', 'LocFull', 'Description', 'LocType', 'CreateDate', 'EndDate'];
protected $useTimestamps = true;
protected $createdField = 'CreateDate';
protected $updatedField = '';
protected $useSoftDeletes = true;
protected $deletedField = 'EndDate';
protected $beforeInsert = ['normalizeDatesToUTC'];
protected $beforeUpdate = ['normalizeDatesToUTC'];
protected $afterFind = ['convertDatesToUTCISO'];
protected $afterInsert = ['convertDatesToUTCISO'];
protected $afterUpdate = ['convertDatesToUTCISO'];
public function getLocations($LocCode, $LocName) {
$sql = $this->select("LocationID, LocCode, Parent, LocFull, LocType, v.VDesc ")
->join("valueset v", "v.VSetID=12 and v.VValue=location.loctype", 'left');
if($LocName != '') { $sql->like('LocFull', $LocName, 'both'); }
if($LocCode != '') { $sql->like('LocCode', $LocCode, 'both'); }
$rows = $sql->get()->getResultArray();
return $rows;
}
public function getLocation($LocationID) {
$rows = $this->select("location.*, la.*, v.*")
->join("locationaddress la", "location.LocationID=la.LocationID", "left")
->join("valueset v", "v.VSetID=12 and v.VValue=location.loctype", "left")
->where('location.LocationID', (int) $LocationID)
->get()->getResultArray();
return $rows;
}
public function saveLocation(array $data): array {
$modelAddress = new \App\Models\Location\LocationAddressModel();
$db = \Config\Database::connect();
$db->transBegin();
try {
if (!empty($data['LocationID'])) {
$LocationID = $data['LocationID'];
$this->update($LocationID, $data);
$modelAddress->update($LocationID, $data);
} else {
$LocationID = $this->insert($data, true);
$data['LocationID'] = $LocationID;
$modelAddress->insert($data);
}
if ($db->transStatus() === false) {
$db->transRollback();
throw new \Exception('Transaction failed');
}
$db->transCommit();
return [ 'status' => 'success', 'LocationID' => $LocationID ];
} catch (\Throwable $e) {
$db->transRollback();
return [ 'status' => 'error', 'message' => $e->getMessage() ];
}
}
public function deleteLocation(array $data): array {
$modelAddress = new \App\Models\Location\LocationAddressModel();
$db = \Config\Database::connect();
$db->transBegin();
try {
$LocationID = $data['LocationID'];
$this->delete($LocationID);
$modelAddress->delete($LocationID);
if ($db->transStatus() === false) {
$db->transRollback();
throw new \Exception('Transaction failed');
}
$db->transCommit();
return [ 'status' => 'success', 'LocationID' => $LocationID ];
} catch (\Throwable $e) {
$db->transRollback();
return [ 'status' => 'error', 'message' => $e->getMessage() ];
}
}
}