| 1 | <?php |
||
| 21 | trait CountAttributeTrait |
||
| 22 | { |
||
| 23 | /** |
||
| 24 | * Returns the aggregate value of a field. |
||
| 25 | * |
||
| 26 | * @param string $field |
||
| 27 | * |
||
| 28 | * @return int |
||
| 29 | */ |
||
| 30 | 8 | protected function getCountAttribute($field) |
|
| 31 | { |
||
| 32 | // if relation is not loaded already, let's do it first |
||
| 33 | 8 | if (!array_key_exists($field, $this->relations)) { |
|
|
|
|||
| 34 | $this->load($field); |
||
| 35 | } |
||
| 36 | |||
| 37 | 8 | $related = $this->getRelation($field); |
|
| 38 | |||
| 39 | // then return the count directly |
||
| 40 | 8 | return ($related) ? (int) $related->aggregate : 0; |
|
| 41 | } |
||
| 42 | |||
| 43 | /** |
||
| 44 | * Eager load relations on the model. |
||
| 45 | * |
||
| 46 | * @param array|string $relations |
||
| 47 | * |
||
| 48 | * @return $this |
||
| 49 | */ |
||
| 50 | abstract public function load($relations); |
||
| 51 | |||
| 52 | /** |
||
| 53 | * Get a specified relationship. |
||
| 54 | * |
||
| 55 | * @param string $relation |
||
| 56 | * |
||
| 57 | * @return mixed |
||
| 58 | */ |
||
| 59 | abstract public function getRelation($relation); |
||
| 60 | } |
||
| 61 |
In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:
Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion: