You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

68 lines
1.5KB

  1. <?php
  2. namespace App\Models;
  3. use Auth;
  4. use Illuminate\Database\Eloquent\Factories\HasFactory;
  5. use Illuminate\Database\Eloquent\Model;
  6. use Illuminate\Support\Facades\DB;
  7. /**
  8. * @property int|null $created_by
  9. */
  10. abstract class BaseModel extends Model
  11. {
  12. use HasFactory;
  13. const COL_NAME_ID = ColumnName::ID;
  14. const COL_NAME_CREATED_BY = 'created_by';
  15. const COL_NAME_CREATED_AT = self::CREATED_AT;
  16. const COL_NAME_UPDATED_AT = self::UPDATED_AT;
  17. public function __construct(array $attr = [])
  18. {
  19. if (Auth::check()) {
  20. $this->created_by = Auth::id();
  21. }
  22. parent::__construct($attr);
  23. }
  24. protected $guarded = [
  25. self::COL_NAME_ID,
  26. ];
  27. public static function getBuilder(string $name = 'main')
  28. {
  29. return DB::table(static::getTableName(), $name);
  30. }
  31. public static function getTableName(): string
  32. {
  33. return (new static)->getTable();
  34. }
  35. public function copy(BaseModel|User $from)
  36. {
  37. $data = $from->getAttributeKeys();
  38. foreach ($data as $key) {
  39. if ($key === ColumnName::ID && $this instanceof BaseHistory) {
  40. continue;
  41. }
  42. $this->$key = $from->$key;
  43. }
  44. return $this;
  45. }
  46. public function getAttributeKeys()
  47. {
  48. return array_values(array_unique(array_merge(array_keys($this->attributesToArray()), $this->hidden)));
  49. }
  50. public function isNotSavedModel(): bool
  51. {
  52. return data_get($this, self::COL_NAME_ID) === null;
  53. }
  54. }