63 lines
1.4 KiB
PHP
63 lines
1.4 KiB
PHP
<?php
|
|
|
|
/**
|
|
* Works out the next ID to use for an Eloquent Table.
|
|
*
|
|
* If we update records, we update the record_id table
|
|
*/
|
|
namespace App\Traits;
|
|
|
|
use Illuminate\Database\Eloquent\ModelNotFoundException;
|
|
use Illuminate\Support\Facades\Log;
|
|
|
|
use App\Models\{Module,Record};
|
|
|
|
trait NextKey
|
|
{
|
|
public static function boot()
|
|
{
|
|
parent::boot();
|
|
|
|
static::creating(function($model)
|
|
{
|
|
$model->id = self::NextId();
|
|
|
|
if (! $model->site_id)
|
|
$model->site_id = config('SITE_SETUP')->id;
|
|
});
|
|
|
|
static::saved(function($model)
|
|
{
|
|
if ($model->wasRecentlyCreated) {
|
|
if (! defined(get_class($model).'::RECORD_ID'))
|
|
throw new \Exception('Missing record_id const for '.get_class($model));
|
|
|
|
try {
|
|
$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) {
|
|
$mo->record = new Record;
|
|
$mo->record->module_id = $mo->id;
|
|
$mo->record->site_id = $model->site_id ?: config('SITE_SETUP')->id;
|
|
}
|
|
|
|
$mo->record->id = $model->id;
|
|
$mo->record->save();
|
|
}
|
|
});
|
|
}
|
|
|
|
public static function NextId()
|
|
{
|
|
return (new self)->max('id')+1;
|
|
}
|
|
} |