|
1
|
|
|
<?php |
|
2
|
|
|
/** |
|
3
|
|
|
* Bluz Framework Component |
|
4
|
|
|
* |
|
5
|
|
|
* @copyright Bluz PHP Team |
|
6
|
|
|
* @link https://github.com/bluzphp/framework |
|
7
|
|
|
*/ |
|
8
|
|
|
|
|
9
|
|
|
declare(strict_types=1); |
|
10
|
|
|
|
|
11
|
|
|
namespace Bluz\Db\Traits; |
|
12
|
|
|
|
|
13
|
|
|
use Bluz\Db\Relations; |
|
14
|
|
|
use Bluz\Db\Row; |
|
15
|
|
|
use Bluz\Db\Exception\RelationNotFoundException; |
|
16
|
|
|
use Bluz\Db\Exception\TableNotFoundException; |
|
17
|
|
|
use Bluz\Db\RowInterface; |
|
18
|
|
|
|
|
19
|
|
|
/** |
|
20
|
|
|
* RowRelations |
|
21
|
|
|
* |
|
22
|
|
|
* @package Bluz\Db\Traits |
|
23
|
|
|
* @author Anton Shevchuk |
|
24
|
|
|
*/ |
|
25
|
|
|
trait RowRelations |
|
26
|
|
|
{ |
|
27
|
|
|
/** |
|
28
|
|
|
* @var array relations rows |
|
29
|
|
|
*/ |
|
30
|
|
|
protected $relations = []; |
|
31
|
|
|
|
|
32
|
|
|
/** |
|
33
|
|
|
* Set relation |
|
34
|
|
|
* |
|
35
|
|
|
* @param Row $row |
|
36
|
|
|
* |
|
37
|
|
|
* @return void |
|
38
|
|
|
* @throws TableNotFoundException |
|
39
|
|
|
*/ |
|
40
|
|
|
public function setRelation(Row $row) : void |
|
41
|
|
|
{ |
|
42
|
|
|
$modelName = $row->getTable()->getModel(); |
|
43
|
|
|
$this->relations[$modelName] = [$row]; |
|
44
|
|
|
} |
|
45
|
|
|
|
|
46
|
|
|
/** |
|
47
|
|
|
* Get relation by model name |
|
48
|
|
|
* |
|
49
|
|
|
* @param string $modelName |
|
50
|
|
|
* |
|
51
|
|
|
* @return RowInterface |
|
52
|
|
|
* @throws RelationNotFoundException |
|
53
|
|
|
* @throws TableNotFoundException |
|
54
|
|
|
*/ |
|
55
|
1 |
|
public function getRelation($modelName) : ?RowInterface |
|
56
|
|
|
{ |
|
57
|
1 |
|
$relations = $this->getRelations($modelName); |
|
58
|
|
|
return empty($relations) ? null : current($relations); |
|
59
|
|
|
} |
|
60
|
|
|
|
|
61
|
|
|
/** |
|
62
|
|
|
* Get relations by model name |
|
63
|
|
|
* |
|
64
|
|
|
* @param string $modelName |
|
65
|
|
|
* |
|
66
|
|
|
* @return RowInterface[] |
|
67
|
|
|
* @throws RelationNotFoundException |
|
68
|
|
|
* @throws TableNotFoundException |
|
69
|
|
|
*/ |
|
70
|
1 |
|
public function getRelations($modelName) : array |
|
71
|
|
|
{ |
|
72
|
1 |
|
if (!isset($this->relations[$modelName])) { |
|
73
|
1 |
|
$this->relations[$modelName] = Relations::findRelation($this, $modelName); |
|
74
|
|
|
} |
|
75
|
|
|
|
|
76
|
|
|
return $this->relations[$modelName]; |
|
77
|
|
|
} |
|
78
|
|
|
} |
|
79
|
|
|
|