blob: 9a9b2f9b63fd730318e1e900f070ffd1fe0bfbe4 [file] [log] [blame]
Matthias Andreas Benkard7b2a3a12021-08-16 10:57:25 +02001<?php
2
3namespace LdapRecord\Models\Relations;
4
5use LdapRecord\Models\Model;
6
7class 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 *
30 * @throws \LdapRecord\LdapRecordException
31 *
32 * @return Model|string
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 *
48 * @throws \LdapRecord\LdapRecordException
49 *
50 * @return void
51 */
52 public function detach()
53 {
54 $this->parent->setAttribute($this->relationKey, null)->save();
55 }
56}