| @@ 21-60 (lines=40) @@ | ||
| 18 | * |
|
| 19 | * @property static $this |
|
| 20 | */ |
|
| 21 | trait CountAttributeTrait |
|
| 22 | { |
|
| 23 | /** |
|
| 24 | * Returns the aggregate value of a field. |
|
| 25 | * |
|
| 26 | * @param string $field |
|
| 27 | * |
|
| 28 | * @return int |
|
| 29 | */ |
|
| 30 | protected function getCountAttribute($field) |
|
| 31 | { |
|
| 32 | // if relation is not loaded already, let's do it first |
|
| 33 | if (!array_key_exists($field, $this->relations)) { |
|
| 34 | $this->load($field); |
|
| 35 | } |
|
| 36 | ||
| 37 | $related = $this->getRelation($field); |
|
| 38 | ||
| 39 | // then return the count directly |
|
| 40 | 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 | ||
| @@ 21-60 (lines=40) @@ | ||
| 18 | * |
|
| 19 | * @property static $this |
|
| 20 | */ |
|
| 21 | trait CountAttributeTrait |
|
| 22 | { |
|
| 23 | /** |
|
| 24 | * Returns the aggregate value of a field. |
|
| 25 | * |
|
| 26 | * @param string $field |
|
| 27 | * |
|
| 28 | * @return int |
|
| 29 | */ |
|
| 30 | protected function getCountAttribute($field) |
|
| 31 | { |
|
| 32 | // if relation is not loaded already, let's do it first |
|
| 33 | if (!array_key_exists($field, $this->relations)) { |
|
| 34 | $this->load($field); |
|
| 35 | } |
|
| 36 | ||
| 37 | $related = $this->getRelation($field); |
|
| 38 | ||
| 39 | // then return the count directly |
|
| 40 | 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 | ||