|
- <?php
-
- namespace App\Models;
-
- use Auth;
- use Illuminate\Database\Eloquent\Factories\HasFactory;
- use Illuminate\Database\Eloquent\Model;
- use Illuminate\Support\Facades\DB;
-
- /**
- * @property int|null $created_by
- */
- abstract class BaseModel extends Model
- {
- use HasFactory;
-
- const COL_NAME_ID = ColumnName::ID;
- const COL_NAME_CREATED_BY = 'created_by';
- const COL_NAME_CREATED_AT = self::CREATED_AT;
- const COL_NAME_UPDATED_AT = self::UPDATED_AT;
-
- public function __construct(array $attr = [])
- {
- if (Auth::check()) {
- $this->created_by = Auth::id();
- }
-
- parent::__construct($attr);
- }
-
- protected $guarded = [
- self::COL_NAME_ID,
- ];
-
- public static function getBuilder(string $name = 'main')
- {
- return DB::table(static::getTableName(), $name);
- }
-
- public static function getTableName(): string
- {
- return (new static)->getTable();
- }
-
- public function copy(BaseModel|User $from)
- {
- $data = $from->getAttributeKeys();
-
- foreach ($data as $key) {
- if ($key === ColumnName::ID && $this instanceof BaseHistory) {
- continue;
- }
- $this->$key = $from->$key;
- }
- return $this;
- }
-
- public function getAttributeKeys()
- {
- return array_values(array_unique(array_merge(array_keys($this->attributesToArray()), $this->hidden)));
- }
-
- public function isNotSavedModel(): bool
- {
- return data_get($this, self::COL_NAME_ID) === null;
- }
- }
|