選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

State.php 2.0KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. <?php
  2. namespace App\Models\Locale;
  3. use Illuminate\Database\Eloquent\Relations\BelongsTo;
  4. use Illuminate\Database\Eloquent\Relations\HasMany;
  5. use Squire\Model;
  6. /**
  7. * @property int $id
  8. * @property string $name
  9. * @property string $country_id
  10. * @property string $country_name
  11. * @property string $state_code
  12. * @property float $latitude
  13. * @property float $longitude
  14. */
  15. class State extends Model
  16. {
  17. public static array $schema = [
  18. 'id' => 'integer',
  19. 'name' => 'string',
  20. 'country_id' => 'string',
  21. 'country_name' => 'string',
  22. 'state_code' => 'string',
  23. 'latitude' => 'float',
  24. 'longitude' => 'float',
  25. ];
  26. public static function getStateOptions(?string $code = null): array
  27. {
  28. if (! $code) {
  29. return [];
  30. }
  31. return self::query()
  32. ->where('country_id', $code)
  33. ->orderBy('name')
  34. ->get()
  35. ->pluck('name', 'id')
  36. ->toArray();
  37. }
  38. public static function getSearchResultsUsing(string $search, ?string $countryCode = null): array
  39. {
  40. if (! $countryCode) {
  41. return [];
  42. }
  43. return self::query()
  44. ->where('country_id', $countryCode)
  45. ->where(static function ($query) use ($search) {
  46. $query->whereLike('name', "%{$search}%")
  47. ->orWhereLike('state_code', "%{$search}%");
  48. })
  49. ->orderByRaw('
  50. CASE
  51. WHEN state_code = ? THEN 1
  52. WHEN state_code LIKE ? THEN 2
  53. WHEN name LIKE ? THEN 3
  54. ELSE 4
  55. END
  56. ', [$search, $search . '%', $search . '%'])
  57. ->limit(50)
  58. ->get()
  59. ->pluck('name', 'id')
  60. ->toArray();
  61. }
  62. public function country(): BelongsTo
  63. {
  64. return $this->belongsTo(Country::class, 'country_id', 'id');
  65. }
  66. public function cities(): HasMany
  67. {
  68. return $this->hasMany(City::class, 'state_id', 'id');
  69. }
  70. }