|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace HexMakina\Crudites\Relation; |
|
4
|
|
|
|
|
5
|
|
|
use HexMakina\BlackBox\Database\ConnectionInterface; |
|
6
|
|
|
use HexMakina\Crudites\Result; |
|
7
|
|
|
|
|
8
|
|
|
class HasOne extends AbstractRelation |
|
9
|
|
|
{ |
|
10
|
|
|
public const NAME = 'hasOne'; |
|
11
|
|
|
|
|
12
|
|
|
public function __construct(string $table, array $join, ConnectionInterface $c) |
|
13
|
|
|
{ |
|
14
|
|
|
$this->setConnection($c); |
|
15
|
|
|
$this->primary_table = $table; |
|
16
|
|
|
$this->propertiesFromJoin($join); |
|
17
|
|
|
} |
|
18
|
|
|
|
|
19
|
|
|
protected function propertiesFromJoin(array $join): void |
|
20
|
|
|
{ |
|
21
|
|
|
$this->primary_col = array_key_first($join); |
|
22
|
|
|
[$this->secondary_table, $this->secondary_col] = $join[$this->primary_col]; |
|
23
|
|
|
} |
|
24
|
|
|
|
|
25
|
|
|
public function link(int $primary_id, $secondary_id): bool |
|
26
|
|
|
{ |
|
27
|
|
|
$data = [ |
|
28
|
|
|
$this->primary_col => $primary_id, |
|
29
|
|
|
$this->secondary_col => $secondary_id |
|
30
|
|
|
]; |
|
31
|
|
|
|
|
32
|
|
|
$query = $this->connection->schema()->insert($this->primary_table, $data); |
|
33
|
|
|
return (new Result($this->connection->pdo(), $query))->ran(); |
|
34
|
|
|
} |
|
35
|
|
|
|
|
36
|
|
|
public function unlink(int $primary_id, $secondary_id): bool |
|
37
|
|
|
{ |
|
38
|
|
|
$criteria = [ |
|
39
|
|
|
$this->primary_col => $primary_id, |
|
40
|
|
|
$this->secondary_col => $secondary_id |
|
41
|
|
|
]; |
|
42
|
|
|
|
|
43
|
|
|
$query = $this->connection->schema()->delete($this->primary_table, $criteria); |
|
44
|
|
|
return (new Result($this->connection->pdo(), $query))->ran(); |
|
45
|
|
|
} |
|
46
|
|
|
} |
|
47
|
|
|
|