BaseModel.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: vien
  5. * Date: 2019/1/31
  6. * Time: 11:26 AM
  7. */
  8. namespace App\Models\Base;
  9. use Illuminate\Database\Eloquent\Model;
  10. use Illuminate\Database\Eloquent\SoftDeletes;
  11. class BaseModel extends Model
  12. {
  13. use SoftDeletes;
  14. protected $allowEmpty = [];
  15. /**
  16. * 需要转换成日期的属性
  17. *
  18. * @var array
  19. */
  20. protected $dates = ['deleted_at'];
  21. /**
  22. * 默认使用时间戳戳功能
  23. *
  24. * @var bool
  25. */
  26. public $timestamps = true;
  27. /**
  28. * 获取当前时间
  29. *
  30. * @return int
  31. */
  32. public function freshTimestamp()
  33. {
  34. return time();
  35. }
  36. /**
  37. * 避免转换时间戳为时间字符串
  38. *
  39. * @param DateTime|int $value
  40. * @return DateTime|int
  41. */
  42. public function fromDateTime($value)
  43. {
  44. return $value;
  45. }
  46. /**
  47. * select的时候避免转换时间为Carbon
  48. *
  49. * @param mixed $value
  50. * @return mixed
  51. */
  52. // protected function asDateTime($value) {
  53. // return $value;
  54. // }
  55. /**
  56. * 从数据库获取的为获取时间戳格式
  57. *
  58. * @return string
  59. */
  60. public function getDateFormat()
  61. {
  62. return 'U';
  63. }
  64. /**
  65. * check column and store
  66. * @param $data
  67. * @return $this|int
  68. */
  69. public function checkStore($data)
  70. {
  71. $validData = array();
  72. foreach ($this->fillable as $key) {
  73. if (isset($data[$key])) {
  74. $validData[$key] = $data[$key];
  75. } elseif (!in_array($key, $this->allowEmpty)) {
  76. return 0;
  77. }
  78. }
  79. return $this->fill($validData)->save();
  80. }
  81. /**
  82. * check column and update
  83. * @param $id
  84. * @param $data
  85. * @return $this|int
  86. */
  87. public function checkUpdate($id, $data)
  88. {
  89. $validData = array();
  90. foreach ($this->fillable as $key) {
  91. if (isset($data[$key])) {
  92. $validData[$key] = $data[$key];
  93. }
  94. }
  95. if ($validData) {
  96. return $this->where('id', $id)->update($validData);
  97. }
  98. return 0;
  99. }
  100. }