2018-08-11 05:09:41 +00:00
|
|
|
<?php
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Works out the next ID to use for an Eloquent Table.
|
2019-06-07 06:54:27 +00:00
|
|
|
*
|
|
|
|
* If we update records, we update the record_id table
|
2018-08-11 05:09:41 +00:00
|
|
|
*/
|
|
|
|
namespace App\Traits;
|
|
|
|
|
2021-06-30 04:18:12 +00:00
|
|
|
use Illuminate\Database\Eloquent\ModelNotFoundException;
|
|
|
|
use Illuminate\Support\Facades\Log;
|
|
|
|
|
2019-06-13 04:32:34 +00:00
|
|
|
use App\Models\{Module,Record};
|
2019-06-07 06:54:27 +00:00
|
|
|
|
2018-08-11 05:09:41 +00:00
|
|
|
trait NextKey
|
|
|
|
{
|
|
|
|
public static function boot()
|
|
|
|
{
|
|
|
|
parent::boot();
|
|
|
|
|
|
|
|
static::creating(function($model)
|
|
|
|
{
|
|
|
|
$model->id = self::NextId();
|
2019-09-03 04:43:59 +00:00
|
|
|
|
|
|
|
if (! $model->site_id)
|
2021-07-02 00:03:36 +00:00
|
|
|
$model->site_id = config('SITE')->site_id;
|
2018-08-11 05:09:41 +00:00
|
|
|
});
|
2019-06-07 06:54:27 +00:00
|
|
|
|
|
|
|
static::saved(function($model)
|
|
|
|
{
|
2019-06-07 12:34:41 +00:00
|
|
|
if ($model->wasRecentlyCreated) {
|
|
|
|
if (! defined(get_class($model).'::RECORD_ID'))
|
|
|
|
throw new \Exception('Missing record_id const for '.get_class($model));
|
2019-06-07 06:54:27 +00:00
|
|
|
|
2021-06-30 04:18:12 +00:00
|
|
|
try {
|
2021-07-02 00:03:36 +00:00
|
|
|
$mo = Module::where('name',$model::RECORD_ID)
|
|
|
|
->where('site_id',$model->site_id)->firstOrFail();
|
2021-06-30 04:18:12 +00:00
|
|
|
|
|
|
|
} 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;
|
2021-07-02 00:03:36 +00:00
|
|
|
$mo->site_id = $model->site_id ?: config('SITE')->site_id;
|
2021-06-30 04:18:12 +00:00
|
|
|
$mo->save();
|
|
|
|
}
|
2019-06-13 04:32:34 +00:00
|
|
|
|
|
|
|
if (! $mo->record) {
|
|
|
|
$mo->record = new Record;
|
|
|
|
$mo->record->module_id = $mo->id;
|
2021-07-02 00:03:36 +00:00
|
|
|
$mo->record->site_id = $model->site_id ?: config('SITE')->site_id;
|
2019-06-13 04:32:34 +00:00
|
|
|
}
|
|
|
|
|
2019-06-07 12:34:41 +00:00
|
|
|
$mo->record->id = $model->id;
|
|
|
|
$mo->record->save();
|
|
|
|
}
|
2019-06-07 06:54:27 +00:00
|
|
|
});
|
2018-08-11 05:09:41 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
public static function NextId()
|
|
|
|
{
|
|
|
|
return (new self)->max('id')+1;
|
|
|
|
}
|
|
|
|
}
|