Files
portal-api/app/Repositories/Module/Host/HostRepository.php
T
2026-01-30 17:08:59 +07:00

98 lines
3.0 KiB
PHP

<?php
namespace App\Repositories\Module\Host;
use App\Models\ModuleHost;
use App\Repositories\BaseRepository;
class HostRepository extends BaseRepository implements HostRepositoryInterface
{
public function getModel()
{
return ModuleHost::class;
}
public function filter(
array $data = [],
array $relationships = [],
array $withCount = [],
array $select = ['*'],
bool $returnQuery = false
) {
$query = $this->model->with($relationships)->select($select);
if (isset($data['module_datacenter_id']) && $data['module_datacenter_id']) {
$query = $query->where("module_datacenter_id", $data['module_datacenter_id']);
}
if (count($withCount) > 0) {
$query = $query->withCount($withCount);
}
if ($returnQuery) {
return $query;
}
if (isset($data['page']) || isset($data['paginate'])) {
return $query->paginate($data['per_page'] ?? 15);
}
return $query->get();
}
public function findWithRelationships(int $id = 0, array $relationships = [], array $withCount = [], array $withSum = [])
{
$model = $this->model;
if (count($relationships) > 0) {
foreach ($relationships as $relationship) {
if (method_exists($model, $relationship)) {
$model = $model->with($relationship);
}
}
}
// Xử lý withCount
if (count($withCount) > 0) {
foreach ($withCount as $key => $items) {
if (is_array($items)) {
foreach ($items as $alias => $item) {
$model = $model->withCount([
$key . ' as ' . $alias => function ($query) use ($item) {
$query->where($item['key'], $item['condition'], $item['value']);
}
]);
}
} else {
$model = $model->withCount($key);
}
}
}
// Xử lý withSum
if (count($withSum) > 0) {
foreach ($withSum as $key => $items) {
if (is_array($items)) {
foreach ($items as $alias => $item) {
$model = $model->withSum([
$key . ' as ' . $alias => function ($query) use ($item) {
$query->where($item['key'], $item['condition'], $item['value']);
}
], $item['sum']);
}
} else {
$model = $model->withSum($key);
}
}
}
return $model->find($id);
}
public function findBy(string $key = '', string|int|null $value = '')
{
if (empty($key) || empty($value)) {
return false;
}
return $this->model->where($key, $value)->first();
}
}