BaseModel.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. <?php
  2. /**
  3. *------------------------------------------------------
  4. * Model层基类
  5. *------------------------------------------------------
  6. *
  7. * @author qqiu@qq.com
  8. * @date 2016/05/26 09:22
  9. * @version V1.0
  10. *
  11. */
  12. namespace App\Models;
  13. use Illuminate\Database\Eloquent\Model;
  14. use Illuminate\Http\Request;
  15. use Illuminate\Support\Facades\Validator;
  16. class BaseModel extends Model
  17. {
  18. /**
  19. * 维护数据表中 created_at 和 updated_at 字段
  20. */
  21. public $timestamps = true;
  22. protected $guarded = [];
  23. protected $statusOptions = [
  24. ['id' => 1, 'name' => '未激活', 'color' => 'gray'],
  25. ['id' => 2, 'name' => '激活', 'color' => 'blue'],
  26. ['id' => 3, 'name' => '禁用', 'color' => 'red']
  27. ];
  28. /**
  29. * 多个Where
  30. * @param Object $query
  31. * @param array $arr ['status' => 1, 'type' => 2]
  32. * @return Object $query
  33. */
  34. public function multiwhere($query, $arr)
  35. {
  36. if ( !is_array($arr) ) {
  37. return $query;
  38. }
  39. foreach ($arr as $key => $value) {
  40. $query = $query->where($key, $value);
  41. }
  42. return $query;
  43. }
  44. public function getValidator(Request $request, $type)
  45. {
  46. $validator = Validator::make($request->input('data'), [
  47. 'name' => 'required'
  48. ], [
  49. 'name.required' => '名称必填'
  50. ]);
  51. return $validator;
  52. }
  53. public static function getOptions()
  54. {
  55. return self::where('id', '>', 0)->orderBy('sort')->get()->toArray();
  56. }
  57. public function getStatusOptions()
  58. {
  59. return $this->statusOptions;
  60. }
  61. /*
  62. * type: name|label
  63. */
  64. public function getStatus($type = 'name') {
  65. $options = $this->statusOptions;
  66. $option = $options[0];
  67. foreach($options as $item) {
  68. if($item['id'] == $this['status']) {
  69. $option = $item;
  70. break;
  71. }
  72. }
  73. if($type == 'name') return $option['name'];
  74. else return '<div class="layui-badge layui-bg-' . $option['color'] . '">' . $option['name'] . '</div>';
  75. }
  76. /**
  77. * @param $column
  78. * @param string $type(name|label)
  79. * @return string
  80. */
  81. public function getNameOrLabel($column, $type = 'name')
  82. {
  83. $option = Option::get($this->getTable(), $column, $this[$column], null);
  84. if(!$option) return '';
  85. if($type == 'name') return $option->name;
  86. else return '<div class="layui-badge layui-bg-' . $option->label_type . '">' . $option->name . '</div>';
  87. }
  88. public function transMoney($money) {
  89. return round($money * 100);
  90. }
  91. }