Matthias Andreas Benkard | 7b2a3a1 | 2021-08-16 10:57:25 +0200 | [diff] [blame] | 1 | <?php |
| 2 | |
| 3 | namespace LdapRecord\Models\Relations; |
| 4 | |
| 5 | use LdapRecord\Models\Model; |
| 6 | |
| 7 | class HasOne extends Relation |
| 8 | { |
| 9 | /** |
| 10 | * Get the results of the relationship. |
| 11 | * |
| 12 | * @return \LdapRecord\Query\Collection |
| 13 | */ |
| 14 | public function getResults() |
| 15 | { |
| 16 | $model = $this->getForeignModelByValue( |
| 17 | $this->getFirstAttributeValue($this->parent, $this->relationKey) |
| 18 | ); |
| 19 | |
| 20 | return $this->transformResults( |
| 21 | $this->parent->newCollection($model ? [$model] : null) |
| 22 | ); |
| 23 | } |
| 24 | |
| 25 | /** |
| 26 | * Attach a model instance to the parent model. |
| 27 | * |
| 28 | * @param Model|string $model |
| 29 | * |
Matthias Andreas Benkard | 7b2a3a1 | 2021-08-16 10:57:25 +0200 | [diff] [blame] | 30 | * @return Model|string |
Matthias Andreas Benkard | 1ba5381 | 2022-12-27 17:32:58 +0100 | [diff] [blame^] | 31 | * |
| 32 | * @throws \LdapRecord\LdapRecordException |
Matthias Andreas Benkard | 7b2a3a1 | 2021-08-16 10:57:25 +0200 | [diff] [blame] | 33 | */ |
| 34 | public function attach($model) |
| 35 | { |
| 36 | $foreign = $model instanceof Model |
| 37 | ? $this->getForeignValueFromModel($model) |
| 38 | : $model; |
| 39 | |
| 40 | $this->parent->setAttribute($this->relationKey, $foreign)->save(); |
| 41 | |
| 42 | return $model; |
| 43 | } |
| 44 | |
| 45 | /** |
| 46 | * Detach the related model from the parent. |
| 47 | * |
Matthias Andreas Benkard | 7b2a3a1 | 2021-08-16 10:57:25 +0200 | [diff] [blame] | 48 | * @return void |
Matthias Andreas Benkard | 1ba5381 | 2022-12-27 17:32:58 +0100 | [diff] [blame^] | 49 | * |
| 50 | * @throws \LdapRecord\LdapRecordException |
Matthias Andreas Benkard | 7b2a3a1 | 2021-08-16 10:57:25 +0200 | [diff] [blame] | 51 | */ |
| 52 | public function detach() |
| 53 | { |
| 54 | $this->parent->setAttribute($this->relationKey, null)->save(); |
| 55 | } |
| 56 | } |