BaseModel.php 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  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 $statusOptions = [
  23. ['id' => 1, 'name' => '未激活', 'color' => 'gray'],
  24. ['id' => 2, 'name' => '激活', 'color' => 'blue'],
  25. ['id' => 3, 'name' => '禁用', 'color' => 'red']
  26. ];
  27. /**
  28. * 多个Where
  29. * @param Object $query
  30. * @param array $arr ['status' => 1, 'type' => 2]
  31. * @return Object $query
  32. */
  33. public function multiwhere($query, $arr)
  34. {
  35. if ( !is_array($arr) ) {
  36. return $query;
  37. }
  38. foreach ($arr as $key => $value) {
  39. $query = $query->where($key, $value);
  40. }
  41. return $query;
  42. }
  43. public function getValidator(Request $request, $type)
  44. {
  45. if($type == 'store') {
  46. $validator = Validator::make($request->input('data'), [
  47. 'name' => 'required'
  48. ], [
  49. 'name.required' => '名称必填'
  50. ]);
  51. } else {
  52. $validator = Validator::make($request->input('data'), [
  53. 'name' => 'required'
  54. ], [
  55. 'name.required' => '名称必填'
  56. ]);
  57. }
  58. return $validator;
  59. }
  60. public function getOptions()
  61. {
  62. return $this->where('id', '>', 0)->orderBy('sort')->get()->toArray();
  63. }
  64. public function getStatusOptions()
  65. {
  66. return $this->statusOptions;
  67. }
  68. /*
  69. * type: name|label
  70. */
  71. public function getStatus($type = 'name') {
  72. $options = $this->statusOptions;
  73. $option = $options[0];
  74. foreach($options as $item) {
  75. if($item['id'] == $this['status']) {
  76. $option = $item;
  77. break;
  78. }
  79. }
  80. if($type == 'name') return $option['name'];
  81. else return '<div class="layui-badge layui-bg-' . $option['color'] . '">' . $option['name'] . '</div>';
  82. }
  83. public function getNameOrLabel($options = [], $type = 'name', $name = 'status')
  84. {
  85. $option = $options[0];
  86. foreach($options as $item) {
  87. if($item['id'] == $this[$name]) {
  88. $option = $item;
  89. break;
  90. }
  91. }
  92. if($type == 'name') return $option['name'];
  93. else return '<div class="layui-badge layui-bg-' . $option['color'] . '">' . $option['name'] . '</div>';
  94. }
  95. }