CdmsMenus.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. <?php
  2. namespace App\Models;
  3. use Encore\Admin\Traits\DefaultDatetimeFormat;
  4. use Encore\Admin\Traits\ModelTree;
  5. use Illuminate\Database\Eloquent\Model;
  6. use Illuminate\Database\Eloquent\Relations\BelongsToMany;
  7. use Illuminate\Support\Facades\DB;
  8. class CdmsMenus extends Model
  9. {
  10. //
  11. use DefaultDatetimeFormat;
  12. use ModelTree {
  13. ModelTree::boot as treeBoot;
  14. }
  15. /**
  16. * The attributes that are mass assignable.
  17. *
  18. * @var array
  19. */
  20. protected $fillable = ['parent_id', 'order', 'title', 'icon', 'uri', 'permission'];
  21. /**
  22. * Create a new Eloquent model instance.
  23. *
  24. * @param array $attributes
  25. */
  26. public function __construct(array $attributes = [])
  27. {
  28. $connection = config('tenancy.database.connection') ?: config('database.default');
  29. $this->setConnection($connection);
  30. $this->setTable(config('tenancy.database.menu_table'));
  31. parent::__construct($attributes);
  32. }
  33. /**
  34. * A Menu belongs to many roles.
  35. *
  36. * @return BelongsToMany
  37. */
  38. public function roles(): BelongsToMany
  39. {
  40. $pivotTable = config('tenancy.database.role_menu_table');
  41. $relatedModel = config('tenancy.database.roles_model');
  42. return $this->belongsToMany($relatedModel, $pivotTable, 'menu_id', 'role_id');
  43. }
  44. /**
  45. * @return array
  46. */
  47. public function allNodes(): array
  48. {
  49. $connection = config('tenancy.database.connection') ?: config('database.default');
  50. $orderColumn = DB::connection($connection)->getQueryGrammar()->wrap($this->orderColumn);
  51. $byOrder = 'ROOT ASC,'.$orderColumn;
  52. $query = static::query();
  53. if (config('tenancy.check_menu_roles') !== false) {
  54. $query->with('roles');
  55. }
  56. return $query->selectRaw('*, '.$orderColumn.' ROOT')->orderByRaw($byOrder)->get()->toArray();
  57. }
  58. /**
  59. * determine if enable menu bind permission.
  60. *
  61. * @return bool
  62. */
  63. public function withPermission()
  64. {
  65. return (bool) config('tenancy.menu_bind_permission');
  66. }
  67. /**
  68. * Detach models from the relationship.
  69. *
  70. * @return void
  71. */
  72. protected static function boot()
  73. {
  74. static::treeBoot();
  75. static::deleting(function ($model) {
  76. $model->roles()->detach();
  77. });
  78. }
  79. }