diff --git a/.env.testing b/.env.testing index ac24c22..eb63915 100644 --- a/.env.testing +++ b/.env.testing @@ -6,7 +6,7 @@ APP_KEY= APP_DEBUG=true APP_URL=http://localhost -LOG_CHANNEL=stack +LOG_CHANNEL=stderr DB_CONNECTION=mysql DB_HOST=mariadb diff --git a/app/Models/Module.php b/app/Models/Module.php index f9e278e..9115935 100644 --- a/app/Models/Module.php +++ b/app/Models/Module.php @@ -4,9 +4,16 @@ namespace App\Models; use Illuminate\Database\Eloquent\Model; +use App\Traits\NextKey; + class Module extends Model { + use NextKey; + + const RECORD_ID = 'module'; + protected $table = 'ab_module'; + public $incrementing = FALSE; public $timestamps = FALSE; public function record() diff --git a/app/Traits/NextKey.php b/app/Traits/NextKey.php index bc5714f..2f149d2 100644 --- a/app/Traits/NextKey.php +++ b/app/Traits/NextKey.php @@ -7,6 +7,9 @@ */ namespace App\Traits; +use Illuminate\Database\Eloquent\ModelNotFoundException; +use Illuminate\Support\Facades\Log; + use App\Models\{Module,Record}; trait NextKey @@ -29,12 +32,22 @@ trait NextKey if (! defined(get_class($model).'::RECORD_ID')) throw new \Exception('Missing record_id const for '.get_class($model)); - $mo = Module::where('name',$model::RECORD_ID)->firstOrFail(); + 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 = 1; // @todo + $mo->record->site_id = $model->site_id ?: config('SITE_SETUP')->id; } $mo->record->id = $model->id;