Change NextKey to create record in Module table if it doesnt exist

This commit is contained in:
Deon George 2021-06-30 14:18:12 +10:00
parent ec738d590c
commit d02df6e98a
No known key found for this signature in database
GPG Key ID: 7670E8DC27415254
3 changed files with 23 additions and 3 deletions

View File

@ -6,7 +6,7 @@ APP_KEY=
APP_DEBUG=true APP_DEBUG=true
APP_URL=http://localhost APP_URL=http://localhost
LOG_CHANNEL=stack LOG_CHANNEL=stderr
DB_CONNECTION=mysql DB_CONNECTION=mysql
DB_HOST=mariadb DB_HOST=mariadb

View File

@ -4,9 +4,16 @@ namespace App\Models;
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Model;
use App\Traits\NextKey;
class Module extends Model class Module extends Model
{ {
use NextKey;
const RECORD_ID = 'module';
protected $table = 'ab_module'; protected $table = 'ab_module';
public $incrementing = FALSE;
public $timestamps = FALSE; public $timestamps = FALSE;
public function record() public function record()

View File

@ -7,6 +7,9 @@
*/ */
namespace App\Traits; namespace App\Traits;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Support\Facades\Log;
use App\Models\{Module,Record}; use App\Models\{Module,Record};
trait NextKey trait NextKey
@ -29,12 +32,22 @@ trait NextKey
if (! defined(get_class($model).'::RECORD_ID')) if (! defined(get_class($model).'::RECORD_ID'))
throw new \Exception('Missing record_id const for '.get_class($model)); throw new \Exception('Missing record_id const for '.get_class($model));
try {
$mo = Module::where('name',$model::RECORD_ID)->firstOrFail(); $mo = Module::where('name',$model::RECORD_ID)->firstOrFail();
} catch (ModelNotFoundException $e) {
Log::critical(sprintf('Module [%s] not recorded, we\'ll create it.',$model::RECORD_ID),['model'=>$model->getAttributes()]);
$mo = new Module;
$mo->name = $model::RECORD_ID;
$mo->site_id = $model->site_id ?: config('SITE_SETUP')->id;
$mo->save();
}
if (! $mo->record) { if (! $mo->record) {
$mo->record = new Record; $mo->record = new Record;
$mo->record->module_id = $mo->id; $mo->record->module_id = $mo->id;
$mo->record->site_id = 1; // @todo $mo->record->site_id = $model->site_id ?: config('SITE_SETUP')->id;
} }
$mo->record->id = $model->id; $mo->record->id = $model->id;