BaseModel.php 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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. 'user_id' => 'required'
  48. ], [
  49. 'user_id.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. public function getNameOrLabel($options = [], $type = 'name', $name = 'status')
  77. {
  78. $option = $options[0];
  79. foreach($options as $item) {
  80. if($item['id'] == $this[$name]) {
  81. $option = $item;
  82. break;
  83. }
  84. }
  85. if($type == 'name') return $option['name'];
  86. else return '<div class="layui-badge layui-bg-' . $option['color'] . '">' . $option['name'] . '</div>';
  87. }
  88. }