-
-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathHasOne.php
More file actions
68 lines (55 loc) · 1.61 KB
/
HasOne.php
File metadata and controls
68 lines (55 loc) · 1.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
<?php
declare(strict_types=1);
namespace Bow\Database\Barry\Relations;
use Bow\Cache\Cache;
use Bow\Database\Barry\Model;
use Bow\Database\Barry\Relation;
class HasOne extends Relation
{
/**
* Create a new belongs to relationship instance.
*
* @param Model $related
* @param Model $parent
* @param string $foreign_key
* @param string $local_key
*/
public function __construct(Model $related, Model $parent, string $foreign_key, string $local_key)
{
$this->local_key = $local_key;
$this->foreign_key = $foreign_key;
parent::__construct($related, $parent);
}
/**
* Get the results of the relationship.
*
* @return Model
*/
public function getResults(): ?Model
{
$key = $this->query->getTable() . ":" . $this->local_key . ":hasone:" . $this->related->getTable() . ":" . $this->foreign_key;
$cache = Cache::store('file')->get($key);
if (!is_null($cache)) {
$related = new $this->related();
$related->setAttributes($cache);
return $related;
}
$result = $this->query->first();
if (!is_null($result)) {
Cache::store('file')->add($key, $result->toArray(), 60);
}
return $result;
}
/**
* Set the base constraints on the relation query.
*
* @return void
*/
public function addConstraints(): void
{
if (!static::$has_constraints) {
return;
}
$this->query = $this->query->where($this->foreign_key, $this->parent->getAttribute($this->local_key));
}
}