Files
kiri-databases/Traits/HasBase.php
T

85 lines
1.6 KiB
PHP
Raw Normal View History

2022-01-09 03:49:51 +08:00
<?php
/**
* Created by PhpStorm.
* User: whwyy
* Date: 2018/4/4 0004
* Time: 15:47
*/
declare(strict_types=1);
namespace Database\Traits;
use Database\ModelInterface;
use Database\Collection;
use Database\Relation;
2023-04-01 17:11:47 +08:00
use Kiri;
2024-11-06 20:59:30 +08:00
use Kiri\Di\Context;
2022-01-09 03:49:51 +08:00
/**
* Class HasBase
* @package Database
*
* @include Query
2023-04-01 17:11:47 +08:00
*
* @method first($name)
* @method all($name)
* @method count($name)
2022-01-09 03:49:51 +08:00
*/
abstract class HasBase implements \Database\Traits\Relation
{
2023-04-20 23:16:36 +08:00
2023-12-12 15:35:35 +08:00
/** @var ModelInterface|Collection */
protected mixed $data = null;
/**
* @var ModelInterface
*/
protected mixed $model;
protected mixed $value = 0;
/**
* HasBase constructor.
* @param string $name
*/
public function __construct(public string $name)
{
}
2023-12-18 18:11:58 +08:00
2023-12-12 15:35:35 +08:00
/**
2023-12-18 18:11:58 +08:00
* @param string $name
* @param array $arguments
* @return $this|mixed
2024-11-06 20:36:59 +08:00
* @throws \Exception
2023-12-12 15:35:35 +08:00
*/
2023-12-18 18:11:58 +08:00
public function __call(string $name, array $arguments)
2023-12-12 15:35:35 +08:00
{
if ($name !== 'get') {
2024-11-06 20:59:30 +08:00
$query = Context::get(Relation::class)->getQuery($this->name);
2024-11-06 20:36:59 +08:00
if (is_null($query)) {
2024-11-06 20:59:30 +08:00
throw new \Exception('Unknown relation key: ' . $this->name);
2024-11-06 20:36:59 +08:00
}
$query->$name(...$arguments);
2023-12-12 15:35:35 +08:00
return $this;
} else {
return $this->get();
}
}
/**
2023-12-18 18:11:58 +08:00
* @param string $name
2023-12-12 15:35:35 +08:00
* @return mixed
*/
2023-12-18 18:11:58 +08:00
public function __get(string $name): mixed
2023-12-12 15:35:35 +08:00
{
if ($this->data === null) {
$this->data = $this->get();
}
return $this->data;
}
2022-01-09 03:49:51 +08:00
}