blob: 7bad4ab63e17b81909dc5d632a5b7c8e9c47c0c3 [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 *
Matthias Andreas Benkard7b2a3a12021-08-16 10:57:25 +020030 * @return Model|string
Matthias Andreas Benkard1ba53812022-12-27 17:32:58 +010031 *
32 * @throws \LdapRecord\LdapRecordException
Matthias Andreas Benkard7b2a3a12021-08-16 10:57:25 +020033 */
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 Benkard7b2a3a12021-08-16 10:57:25 +020048 * @return void
Matthias Andreas Benkard1ba53812022-12-27 17:32:58 +010049 *
50 * @throws \LdapRecord\LdapRecordException
Matthias Andreas Benkard7b2a3a12021-08-16 10:57:25 +020051 */
52 public function detach()
53 {
54 $this->parent->setAttribute($this->relationKey, null)->save();
55 }
56}