Files
kiri-databases/Traits/HasBase.php
T

82 lines
1.6 KiB
PHP
Raw Normal View History

2021-08-11 15:03:28 +08:00
<?php
/**
* Created by PhpStorm.
* User: whwyy
* Date: 2018/4/4 0004
* Time: 15:47
*/
declare(strict_types=1);
namespace Database\Traits;
2021-09-28 18:54:07 +08:00
use Database\ModelInterface;
2021-08-11 15:03:28 +08:00
use Database\Collection;
use Database\Relation;
use Exception;
/**
* Class HasBase
* @package Database
*
* @include Query
*/
2021-08-17 16:22:18 +08:00
abstract class HasBase implements \Database\Traits\Relation
2021-08-11 15:03:28 +08:00
{
2021-09-28 18:54:07 +08:00
/** @var ModelInterface|Collection */
protected Collection|ModelInterface $data;
2021-08-11 15:03:28 +08:00
/**
2021-09-28 18:54:07 +08:00
* @var ModelInterface
2021-08-11 15:03:28 +08:00
*/
protected mixed $model;
protected mixed $value = [];
/** @var Relation $_relation */
protected Relation $_relation;
/**
* HasBase constructor.
2021-09-28 18:54:07 +08:00
* @param ModelInterface $model
2021-08-11 15:03:28 +08:00
* @param $primaryId
* @param $value
* @param Relation $relation
* @throws Exception
*/
public function __construct(mixed $model, $primaryId, $value, Relation $relation)
{
if (!class_exists($model)) {
2021-09-28 18:54:07 +08:00
throw new Exception('Model must implement ' . $model);
2021-08-11 15:03:28 +08:00
}
2021-09-28 18:54:07 +08:00
if (!in_array(ModelInterface::class, class_implements($model))) {
throw new Exception('Model must implement ' . $model);
2021-08-11 15:03:28 +08:00
}
if (is_array($value)) {
if (empty($value)) $value = [];
2021-09-28 18:54:07 +08:00
$_model = $model::query()->whereIn($primaryId, $value);
2021-08-11 15:03:28 +08:00
} else {
2021-09-28 18:54:07 +08:00
$_model = $model::query()->where(['t1.' . $primaryId => $value]);
2021-08-11 15:03:28 +08:00
}
$this->_relation = $relation->bindIdentification($model, $_model);
$this->model = $model;
$this->value = $value;
}
/**
* @param $name
* @return mixed
*/
public function __get($name): mixed
{
if (empty($this->value)) {
return null;
}
return $this->get();
}
}