fykosak/nette-orm

v0.5.0 2022-10-19 15:38 UTC

This package is auto-updated.

Last update: 2024-09-23 21:53:05 UTC


README

GitHub branch checks state

安装

创建 ORM 模型

<?php 
/**
 * @property-read string name
 * @property-read int event_id
 * @property-read \DateTimeInterface begin
 * @property-read \DateTimeInterface end
 * @note better typehinting for your IDE
 */
class ModelEvent extends AbstractModel {
    // you can define realtions
    public function getParticipants(): GroupedSelection {
        return $this->related('participant', 'event_id');
    }
    // you can define own metods
    public function __toArray(): array {
        return [
            'eventId' => $this->event_id,          
            'begin' => $this->begin ? $this->begin->format('c') : null,
            'end' => $this->end ? $this->end->format('c') : null,          
            'name' => $this->name,
        ];
    }
}

创建 ORM 服务

<?php

class ServiceEvent extends AbstractService {

    public function getNextEvents(): TypedTableSelection {
        return $this->getTable()->where('begin > NOW()');
    }
}

注册扩展

orm:
    <table_name>:
        service: 'FQN of service'
        model: 'FQN of model'
    <another_table_name>:
        service: 'FQN of another service'
        model: 'FQN of another model'
extensions:
    orm: Fykosak\NetteORM\ORMExtension

示例

TypedTableSelection 是一个常规选择,您可以像在 nette DB Selection 中一样使用所有方法。

$query= $sericeEvent->getNextEvent();
$query->where('name','My cool event');

TypedTableSelection 返回 ORM 模型而不是 ActiveRow,但 ORM 模型是 ActiveRow 的子类。

$query= $sericeEvent->getNextEvent();
foreach($query as $event){
$event // event is a ModelEvent
}

$model = $sericeEvent->getNextEvent()->fetch(); // Model is a ModelEvent too.

请注意,GroupedSelection 仍然返回 ActiveRow,您可以使用静态方法 createFromActiveRow

$query= $sericeEvent->getParticipants();
foreach($query as $row){
// $row is a ActiveRow
$participant = ModelParticipant::createFromActiveRow($row);
}

通过方法定义模型之间的关系

class ModelParticipant extends AbstractModel {
    // use ActiveRow to resolve relations and next create a Model.
    public function getEvent(): ModelEvent {
        return  ModelEvent::createFromActiveRow($this->event);
    }
}

现在您可以使用 ReferencedAccessor 访问模型

$myModel // any model that has define single method returned ModelEvent
$modelEvent = ReferencedAccessor::accessModel($myModel,ModelEvent::class);