Relationships

This commit is contained in:
2020-01-21 12:05:21 -03:00
parent bef1b08d0e
commit ccaf1fc5bc
2 changed files with 38 additions and 6 deletions

View File

@ -143,4 +143,10 @@ abstract class Model extends BaseModel implements ModelInterface {
public function jsonSerialize() {
return $this->toArray();
}
public function setRelationship(string $class_name): Relationship {
return (new Relationship)
->setFactory($this->container->get('model'))
->setStart($class_name);
}
}

View File

@ -8,26 +8,52 @@ class Relationship {
protected $start;
protected $nodes;
public function __construct(string $class_name) {
$this->setStart($class_name);
public function __construct(string $class_name = '') {
if ($class_name != '') {
$this->setStart($class_name);
}
}
public function setStart(string $class_name) {
public function setStart(string $class_name): Relationship {
$this->start = (object) [
'class' => $class_name,
'table' => Model::getTable($class_name)
];
return $this;
}
public function addNode(RelationNode $node) {
protected $factory;
public function setFactory(ModelFactory $factory): Relationship {
$this->factory = $factory;
return $this;
}
public function with(string $from_class, string $from_key, string $to_class, string $to_key): Relationship {
$node = (new RelationNode())
->setSource($from_class, $from_key)
->setDestination($to_class, $to_key);
if ($this->nodes === null) {
$this->nodes = [];
}
$this->nodes []= $node;
return $this;
}
public function build(ModelFactory $factory): ModelFactory {
protected $condition;
public function setCondition(string $class_name, string $key, $value): Relationship {
$this->condition = (object) [
'class' => $class_name,
'table' => Model::getTable($class_name),
'key' => $key,
'value' => $value
];
return $this;
}
public function build(): ModelFactory {
$output = $factory->find($this->start->class);
foreach ($this->nodes as $node) {
$output = $node->build($factory);
$output = $node->build($output);
}
$output = $output->where([
implode('.', [$this->condition->table, $this->condition->key]),
$this->condition->value
]);
return $output;
}
}