BaseModel.php 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  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. if($type == 'store') {
  47. $validator = Validator::make($request->input('data'), [
  48. 'name' => 'required'
  49. ], [
  50. 'name.required' => '名称必填'
  51. ]);
  52. } else {
  53. $validator = Validator::make($request->input('data'), [
  54. 'name' => 'required'
  55. ], [
  56. 'name.required' => '名称必填'
  57. ]);
  58. }
  59. return $validator;
  60. }
  61. public function getOptions()
  62. {
  63. return $this->where('id', '>', 0)->orderBy('sort')->get()->toArray();
  64. }
  65. public function getStatusOptions()
  66. {
  67. return $this->statusOptions;
  68. }
  69. /*
  70. * type: name|label
  71. */
  72. public function getStatus($type = 'name') {
  73. $options = $this->statusOptions;
  74. $option = $options[0];
  75. foreach($options as $item) {
  76. if($item['id'] == $this['status']) {
  77. $option = $item;
  78. break;
  79. }
  80. }
  81. if($type == 'name') return $option['name'];
  82. else return '<div class="layui-badge layui-bg-' . $option['color'] . '">' . $option['name'] . '</div>';
  83. }
  84. public function getNameOrLabel($options = [], $type = 'name', $name = 'status')
  85. {
  86. $option = $options[0];
  87. foreach($options as $item) {
  88. if($item['id'] == $this[$name]) {
  89. $option = $item;
  90. break;
  91. }
  92. }
  93. if($type == 'name') return $option['name'];
  94. else return '<div class="layui-badge layui-bg-' . $option['color'] . '">' . $option['name'] . '</div>';
  95. }
  96. }