1 | <?php |
||
2 | /** |
||
3 | * Cycle ORM Schema Builder. |
||
4 | * |
||
5 | * @license MIT |
||
6 | * @author Anton Titov (Wolfy-J) |
||
7 | */ |
||
8 | declare(strict_types=1); |
||
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 | /** |
||
18 | * Similar to BelongsTo relation but does not force external object to always exists. |
||
19 | */ |
||
20 | final class RefersTo extends RelationSchema |
||
21 | { |
||
22 | use FieldTrait, ForeignKeyTrait; |
||
23 | |||
24 | // internal relation type |
||
25 | protected const RELATION_TYPE = Relation::REFERS_TO; |
||
26 | |||
27 | // relation schema options |
||
28 | protected const RELATION_SCHEMA = [ |
||
29 | // save with parent |
||
30 | Relation::CASCADE => true, |
||
31 | |||
32 | // nullable by default |
||
33 | Relation::NULLABLE => true, |
||
34 | |||
35 | // link to parent entity primary key by default |
||
36 | Relation::INNER_KEY => '{relation}_{outerKey}', |
||
37 | |||
38 | // default field name for inner key |
||
39 | Relation::OUTER_KEY => '{target:primaryKey}', |
||
40 | |||
41 | // rendering options |
||
42 | RelationSchema::INDEX_CREATE => true, |
||
43 | RelationSchema::FK_CREATE => true, |
||
44 | RelationSchema::FK_ACTION => 'SET NULL' |
||
45 | ]; |
||
46 | |||
47 | /** |
||
48 | * @param Registry $registry |
||
49 | */ |
||
50 | public function compute(Registry $registry) |
||
51 | { |
||
52 | parent::compute($registry); |
||
53 | |||
54 | $source = $registry->getEntity($this->source); |
||
55 | $target = $registry->getEntity($this->target); |
||
56 | |||
57 | // create target outer field |
||
58 | $this->ensureField( |
||
59 | $source, |
||
60 | $this->options->get(Relation::INNER_KEY), |
||
61 | $this->getField($target, Relation::OUTER_KEY), |
||
62 | $this->options->get(Relation::NULLABLE) |
||
0 ignored issues
–
show
Bug
introduced
by
Loading history...
|
|||
63 | ); |
||
64 | } |
||
65 | |||
66 | /** |
||
67 | * @param Registry $registry |
||
68 | */ |
||
69 | public function render(Registry $registry) |
||
70 | { |
||
71 | $source = $registry->getEntity($this->source); |
||
72 | $target = $registry->getEntity($this->target); |
||
73 | |||
74 | $innerField = $this->getField($source, Relation::INNER_KEY); |
||
75 | $outerField = $this->getField($target, Relation::OUTER_KEY); |
||
76 | |||
77 | $table = $registry->getTableSchema($source); |
||
78 | |||
79 | if ($this->options->get(self::INDEX_CREATE)) { |
||
80 | $table->index([$innerField->getColumn()]); |
||
81 | } |
||
82 | |||
83 | if ($this->options->get(self::FK_CREATE)) { |
||
84 | $this->createForeignKey($registry, $target, $source, $outerField, $innerField); |
||
85 | } |
||
86 | } |
||
87 | } |