1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace App; |
4
|
|
|
|
5
|
|
|
use Illuminate\Database\Eloquent\Model; |
6
|
|
|
use Illuminate\Support\Facades\DB; |
7
|
|
|
|
8
|
|
|
class Location extends Model |
9
|
|
|
{ |
10
|
|
|
/** |
11
|
|
|
* The attributes that are mass assignable. |
12
|
|
|
* |
13
|
|
|
* @var array |
14
|
|
|
*/ |
15
|
|
|
protected $fillable = [ |
16
|
|
|
'name', 'site_id' |
17
|
|
|
]; |
18
|
|
|
|
19
|
|
|
public $timestamps = false; |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* Get the site for the location |
23
|
|
|
*/ |
24
|
|
|
public function site() |
25
|
|
|
{ |
26
|
|
|
return $this->belongsTo('App\Site', 'site_id'); |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
/** |
30
|
|
|
* Get devices for the location |
31
|
|
|
*/ |
32
|
|
|
public function devices() |
33
|
|
|
{ |
34
|
|
|
return $this->hasMany('App\Device'); |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
/** |
38
|
|
|
* Get all the locations with the supplied site id |
39
|
|
|
* |
40
|
|
|
* @param int $site_id |
41
|
|
|
* @return Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection |
42
|
|
|
*/ |
43
|
|
|
public function getLocationsBasedOnSite($site_id) |
44
|
|
|
{ |
45
|
|
|
return self::where('site_id', $site_id)->get(); |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
/** |
49
|
|
|
* Get the locations that are related to the supplied site id and sort the locations |
50
|
|
|
* starting with the supplied location id |
51
|
|
|
* |
52
|
|
|
* @param int $site_id |
53
|
|
|
* @param int $location_id |
54
|
|
|
* @return Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection |
55
|
|
|
*/ |
56
|
|
View Code Duplication |
public function orderedSiteLocationsBy($site_id, $location_id) |
|
|
|
|
57
|
|
|
{ |
58
|
|
|
$locations = self::query()->select(['id', 'name']) |
|
|
|
|
59
|
|
|
->where('site_id', '=', $site_id) |
60
|
|
|
->orderByRaw(DB::raw("(id = " . $location_id . ") DESC")) |
61
|
|
|
->get(); |
62
|
|
|
return $locations; |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
/** |
66
|
|
|
* Create a new location and return its id |
67
|
|
|
* |
68
|
|
|
* @param string $name |
69
|
|
|
* @param int $site_id |
70
|
|
|
* @return int $id |
71
|
|
|
*/ |
72
|
|
|
public function createLocation($name, $site_id) |
73
|
|
|
{ |
74
|
|
|
$location = new Location; |
75
|
|
|
$location->name = $name; |
|
|
|
|
76
|
|
|
$location->site_id = $site_id; |
|
|
|
|
77
|
|
|
$location->save(); |
78
|
|
|
|
79
|
|
|
return $location->id; |
|
|
|
|
80
|
|
|
} |
81
|
|
|
} |
82
|
|
|
|
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.