|
1
|
|
|
<?php |
|
2
|
|
|
declare(strict_types=1); |
|
3
|
|
|
/** |
|
4
|
|
|
* Spiral Framework. |
|
5
|
|
|
* |
|
6
|
|
|
* @license MIT |
|
7
|
|
|
* @author Anton Titov (Wolfy-J) |
|
8
|
|
|
*/ |
|
9
|
|
|
|
|
10
|
|
|
namespace Cycle\Schema\Relation; |
|
11
|
|
|
|
|
12
|
|
|
use Cycle\ORM\Relation; |
|
13
|
|
|
use Cycle\Schema\Registry; |
|
14
|
|
|
use Cycle\Schema\Relation\Traits\FieldTrait; |
|
15
|
|
|
use Cycle\Schema\Relation\Traits\ForeignKeyTrait; |
|
16
|
|
|
|
|
17
|
|
|
class BelongsTo extends RelationSchema |
|
18
|
|
|
{ |
|
19
|
|
|
use FieldTrait, ForeignKeyTrait; |
|
20
|
|
|
|
|
21
|
|
|
protected const RELATION_TYPE = Relation::BELONGS_TO; |
|
22
|
|
|
|
|
23
|
|
|
protected const OPTION_SCHEMA = [ |
|
24
|
|
|
// save with parent |
|
25
|
|
|
Relation::CASCADE => true, |
|
26
|
|
|
|
|
27
|
|
|
// use outer entity constrain by default |
|
28
|
|
|
Relation::CONSTRAIN => true, |
|
29
|
|
|
|
|
30
|
|
|
// nullable by default |
|
31
|
|
|
Relation::NULLABLE => true, |
|
32
|
|
|
|
|
33
|
|
|
// link to parent entity primary key by default |
|
34
|
|
|
Relation::INNER_KEY => '{relation}_{outerKey}', |
|
35
|
|
|
|
|
36
|
|
|
// default field name for inner key |
|
37
|
|
|
Relation::OUTER_KEY => '{target:primaryKey}', |
|
38
|
|
|
|
|
39
|
|
|
// rendering options |
|
40
|
|
|
RelationSchema::FK_CREATE => true, |
|
41
|
|
|
RelationSchema::FK_ACTION => 'CASCADE', |
|
42
|
|
|
RelationSchema::INDEX_CREATE => true, |
|
43
|
|
|
]; |
|
44
|
|
|
|
|
45
|
|
|
/** |
|
46
|
|
|
* @param Registry $registry |
|
47
|
|
|
*/ |
|
48
|
|
|
public function compute(Registry $registry) |
|
49
|
|
|
{ |
|
50
|
|
|
parent::compute($registry); |
|
51
|
|
|
|
|
52
|
|
|
$source = $registry->getEntity($this->source); |
|
53
|
|
|
$target = $registry->getEntity($this->target); |
|
54
|
|
|
|
|
55
|
|
|
// create target outer field |
|
56
|
|
|
$this->ensureField( |
|
57
|
|
|
$source, |
|
58
|
|
|
$this->options->get(Relation::INNER_KEY), |
|
59
|
|
|
$this->getField($target, Relation::OUTER_KEY) |
|
60
|
|
|
); |
|
61
|
|
|
} |
|
62
|
|
|
|
|
63
|
|
|
/** |
|
64
|
|
|
* @param Registry $registry |
|
65
|
|
|
*/ |
|
66
|
|
|
public function render(Registry $registry) |
|
67
|
|
|
{ |
|
68
|
|
|
$source = $registry->getEntity($this->source); |
|
69
|
|
|
$target = $registry->getEntity($this->target); |
|
70
|
|
|
|
|
71
|
|
|
$innerField = $this->getField($source, Relation::INNER_KEY); |
|
72
|
|
|
$outerField = $this->getField($target, Relation::OUTER_KEY); |
|
73
|
|
|
|
|
74
|
|
|
$table = $registry->getTableSchema($source); |
|
75
|
|
|
|
|
76
|
|
|
if ($this->options->get(self::INDEX_CREATE)) { |
|
77
|
|
|
$table->index([$innerField->getColumn()]); |
|
78
|
|
|
} |
|
79
|
|
|
|
|
80
|
|
|
if ($this->options->get(self::FK_CREATE)) { |
|
81
|
|
|
$this->createForeignKey($registry, $target, $source, $outerField, $innerField); |
|
82
|
|
|
} |
|
83
|
|
|
} |
|
84
|
|
|
} |