initial commit
This commit is contained in:
commit
3f64f4a49a
221 files changed
+26665
No files matched your search
@@ -0,0 +1,47 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Rsgrinko\Proton\Database\Model\Relations;
|
||||
|
||||
use Rsgrinko\Proton\Database\Model\Model;
|
||||
|
||||
/**
|
||||
* «Мой хозяин»: внешний ключ лежит у нас. У заметки есть автор —
|
||||
* $note->belongsTo(User::class) по note.user_id.
|
||||
*/
|
||||
final class BelongsTo extends Relation
|
||||
{
|
||||
public function result(): ?Model
|
||||
{
|
||||
$key = $this->parent->raw($this->foreignKey);
|
||||
|
||||
if ($key === null || $key === '' || $key === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $this->query()->where($this->localKey, $key)->first();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, Model> $models
|
||||
*/
|
||||
public function load(string $name, array $models): void
|
||||
{
|
||||
$keys = $this->keys($models, $this->foreignKey);
|
||||
|
||||
if ($keys === []) {
|
||||
return;
|
||||
}
|
||||
|
||||
$owners = [];
|
||||
|
||||
foreach ($this->query()->whereIn($this->localKey, $keys)->get() as $owner) {
|
||||
$owners[(string) $owner->raw($this->localKey)] = $owner;
|
||||
}
|
||||
|
||||
foreach ($models as $model) {
|
||||
$model->setRelation($name, $owners[(string) $model->raw($this->foreignKey)] ?? null);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Rsgrinko\Proton\Database\Model\Relations;
|
||||
|
||||
use Rsgrinko\Proton\Database\Connection;
|
||||
use Rsgrinko\Proton\Database\Model\Model;
|
||||
|
||||
/**
|
||||
* «Многие ко многим» через таблицу-связку: у роли много прав, у пользователя
|
||||
* много проектов. Сама связка — обычная таблица из двух ключей, своей модели
|
||||
* ей не нужно.
|
||||
*/
|
||||
final class BelongsToMany extends Relation
|
||||
{
|
||||
private string $pivot;
|
||||
|
||||
/** Колонка связки, указывающая на связанную модель */
|
||||
private string $relatedKey;
|
||||
|
||||
/**
|
||||
* @param class-string<Model> $related
|
||||
*/
|
||||
public function __construct(Model $parent, string $related, string $pivot, string $foreignKey, string $relatedKey)
|
||||
{
|
||||
parent::__construct($parent, $related, $foreignKey, $parent->keyName());
|
||||
|
||||
$this->pivot = $pivot;
|
||||
$this->relatedKey = $relatedKey;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<int, Model>
|
||||
*/
|
||||
public function result(): array
|
||||
{
|
||||
$key = $this->parent->raw($this->localKey);
|
||||
|
||||
if ($key === null) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$ids = $this->db()->table($this->pivot)
|
||||
->where($this->foreignKey, $key)
|
||||
->pluck($this->relatedKey);
|
||||
|
||||
if ($ids === []) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$instance = new ($this->related)();
|
||||
|
||||
return $this->query()->whereIn($instance->keyName(), array_values($ids))->get();
|
||||
}
|
||||
|
||||
/**
|
||||
* Привязать запись, если её ещё нет в связке.
|
||||
*/
|
||||
public function attach(int|string $id): void
|
||||
{
|
||||
$exists = $this->db()->table($this->pivot)
|
||||
->where($this->foreignKey, $this->parent->raw($this->localKey))
|
||||
->where($this->relatedKey, $id)
|
||||
->exists();
|
||||
|
||||
if ($exists) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->db()->insert($this->pivot, [
|
||||
$this->foreignKey => $this->parent->raw($this->localKey),
|
||||
$this->relatedKey => $id,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Отвязать запись.
|
||||
*/
|
||||
public function detach(int|string $id): void
|
||||
{
|
||||
$this->db()->delete($this->pivot, [
|
||||
$this->foreignKey => $this->parent->raw($this->localKey),
|
||||
$this->relatedKey => $id,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Оставить в связке ровно этот список: чего нет — добавить, лишнее — убрать.
|
||||
*
|
||||
* @param array<int, int|string> $ids
|
||||
*/
|
||||
public function sync(array $ids): void
|
||||
{
|
||||
$current = array_map(
|
||||
'strval',
|
||||
array_values($this->db()->table($this->pivot)
|
||||
->where($this->foreignKey, $this->parent->raw($this->localKey))
|
||||
->pluck($this->relatedKey))
|
||||
);
|
||||
|
||||
$wanted = array_map('strval', $ids);
|
||||
|
||||
foreach (array_diff($wanted, $current) as $id) {
|
||||
$this->attach($id);
|
||||
}
|
||||
|
||||
foreach (array_diff($current, $wanted) as $id) {
|
||||
$this->detach($id);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, Model> $models
|
||||
*/
|
||||
public function load(string $name, array $models): void
|
||||
{
|
||||
$keys = $this->keys($models, $this->localKey);
|
||||
|
||||
if ($keys === []) {
|
||||
return;
|
||||
}
|
||||
|
||||
$links = $this->db()->table($this->pivot)
|
||||
->whereIn($this->foreignKey, $keys)
|
||||
->get();
|
||||
|
||||
if ($links === []) {
|
||||
foreach ($models as $model) {
|
||||
$model->setRelation($name, []);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$instance = new ($this->related)();
|
||||
$ids = array_values(array_unique(array_map(
|
||||
fn (array $row): mixed => $row[$this->relatedKey],
|
||||
$links
|
||||
)));
|
||||
|
||||
$related = [];
|
||||
|
||||
foreach ($this->query()->whereIn($instance->keyName(), $ids)->get() as $model) {
|
||||
$related[(string) $model->key()] = $model;
|
||||
}
|
||||
|
||||
$grouped = [];
|
||||
|
||||
foreach ($links as $link) {
|
||||
$target = $related[(string) $link[$this->relatedKey]] ?? null;
|
||||
|
||||
if ($target !== null) {
|
||||
$grouped[(string) $link[$this->foreignKey]][] = $target;
|
||||
}
|
||||
}
|
||||
|
||||
foreach ($models as $model) {
|
||||
$model->setRelation($name, $grouped[(string) $model->raw($this->localKey)] ?? []);
|
||||
}
|
||||
}
|
||||
|
||||
private function db(): Connection
|
||||
{
|
||||
return $this->parent->connection();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Rsgrinko\Proton\Database\Model\Relations;
|
||||
|
||||
use Rsgrinko\Proton\Database\Model\Model;
|
||||
|
||||
/**
|
||||
* «Много моих»: чужие записи ссылаются на нас своим внешним ключом.
|
||||
* У пользователя — заметки: $user->hasMany(Note::class) по note.user_id.
|
||||
*/
|
||||
class HasMany extends Relation
|
||||
{
|
||||
/**
|
||||
* @return array<int, Model>
|
||||
*/
|
||||
public function result(): array
|
||||
{
|
||||
$key = $this->parent->raw($this->localKey);
|
||||
|
||||
if ($key === null) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return $this->query()->where($this->foreignKey, $key)->get();
|
||||
}
|
||||
|
||||
/**
|
||||
* Новая запись на этой стороне связи — внешний ключ проставляется сам.
|
||||
*
|
||||
* @param array<string, mixed> $attributes
|
||||
*/
|
||||
public function create(array $attributes): Model
|
||||
{
|
||||
$model = new ($this->related)($attributes);
|
||||
|
||||
$model->setAttribute($this->foreignKey, $this->parent->raw($this->localKey));
|
||||
$model->save();
|
||||
|
||||
return $model;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, Model> $models
|
||||
*/
|
||||
public function load(string $name, array $models): void
|
||||
{
|
||||
$keys = $this->keys($models, $this->localKey);
|
||||
|
||||
if ($keys === []) {
|
||||
return;
|
||||
}
|
||||
|
||||
$grouped = [];
|
||||
|
||||
foreach ($this->query()->whereIn($this->foreignKey, $keys)->get() as $related) {
|
||||
$grouped[(string) $related->raw($this->foreignKey)][] = $related;
|
||||
}
|
||||
|
||||
foreach ($models as $model) {
|
||||
$model->setRelation($name, $grouped[(string) $model->raw($this->localKey)] ?? []);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Rsgrinko\Proton\Database\Model\Relations;
|
||||
|
||||
use Rsgrinko\Proton\Database\Model\Model;
|
||||
|
||||
/**
|
||||
* «Один мой»: то же, что HasMany, только запись ожидается одна —
|
||||
* профиль пользователя, настройки, последняя сессия.
|
||||
*/
|
||||
final class HasOne extends HasMany
|
||||
{
|
||||
public function result(): ?Model
|
||||
{
|
||||
$key = $this->parent->raw($this->localKey);
|
||||
|
||||
if ($key === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $this->query()->where($this->foreignKey, $key)->first();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, Model> $models
|
||||
*/
|
||||
public function load(string $name, array $models): void
|
||||
{
|
||||
$keys = $this->keys($models, $this->localKey);
|
||||
|
||||
if ($keys === []) {
|
||||
return;
|
||||
}
|
||||
|
||||
$found = [];
|
||||
|
||||
foreach ($this->query()->whereIn($this->foreignKey, $keys)->get() as $related) {
|
||||
$found[(string) $related->raw($this->foreignKey)] ??= $related;
|
||||
}
|
||||
|
||||
foreach ($models as $model) {
|
||||
$model->setRelation($name, $found[(string) $model->raw($this->localKey)] ?? null);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Rsgrinko\Proton\Database\Model\Relations;
|
||||
|
||||
use Rsgrinko\Proton\Database\Model\Model;
|
||||
use Rsgrinko\Proton\Database\Model\Query;
|
||||
|
||||
/**
|
||||
* Связь между моделями.
|
||||
*
|
||||
* Умеет две вещи: достать результат для одной записи ($user->posts) и подгрузить
|
||||
* связь сразу для списка записей (Query::with('posts')) — одним запросом на связь,
|
||||
* а не по запросу на строку. Второе и есть причина, по которой связь оформлена
|
||||
* объектом, а не методом, возвращающим сразу данные.
|
||||
*/
|
||||
abstract class Relation
|
||||
{
|
||||
protected Model $parent;
|
||||
|
||||
/** @var class-string<Model> */
|
||||
protected string $related;
|
||||
|
||||
protected string $foreignKey;
|
||||
|
||||
protected string $localKey;
|
||||
|
||||
/**
|
||||
* @param class-string<Model> $related
|
||||
*/
|
||||
public function __construct(Model $parent, string $related, string $foreignKey, string $localKey)
|
||||
{
|
||||
$this->parent = $parent;
|
||||
$this->related = $related;
|
||||
$this->foreignKey = $foreignKey;
|
||||
$this->localKey = $localKey;
|
||||
}
|
||||
|
||||
/**
|
||||
* Построитель по связанной модели — на него можно навесить свои условия:
|
||||
* $user->posts()->where('published', 1)->get().
|
||||
*/
|
||||
public function query(): Query
|
||||
{
|
||||
return ($this->related)::query();
|
||||
}
|
||||
|
||||
/**
|
||||
* Результат связи для одной записи.
|
||||
*/
|
||||
abstract public function result(): mixed;
|
||||
|
||||
/**
|
||||
* Подгружает связь сразу для списка моделей.
|
||||
*
|
||||
* @param array<int, Model> $models
|
||||
*/
|
||||
abstract public function load(string $name, array $models): void;
|
||||
|
||||
/**
|
||||
* Собирает значения ключа у списка моделей — по ним и идёт один общий запрос.
|
||||
*
|
||||
* @param array<int, Model> $models
|
||||
*
|
||||
* @return array<int, mixed>
|
||||
*/
|
||||
protected function keys(array $models, string $column): array
|
||||
{
|
||||
$keys = [];
|
||||
|
||||
foreach ($models as $model) {
|
||||
$value = $model->raw($column);
|
||||
|
||||
if ($value !== null && !in_array($value, $keys, true)) {
|
||||
$keys[] = $value;
|
||||
}
|
||||
}
|
||||
|
||||
return $keys;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user