bp/app/Models/Traits/TenantScopedModel.php

52 lines
1.6 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
namespace App\Models\Traits;
use CodeIgniter\Model;
/**
* Trait TenantScopedModel
*
* Обеспечивает автоматическую фильтрацию данных по активной организации.
* Использует organization_id из сессии пользователя.
*/
trait TenantScopedModel
{
/**
* Фильтрует запрос по текущей активной организации из сессии.
*
* Применение:
* $clients = $this->clientModel->forCurrentOrg()->findAll();
* $client = $this->clientModel->forCurrentOrg()->find($id);
*
* @return $this
*/
public function forCurrentOrg()
{
$session = session();
$orgId = $session->get('active_org_id');
// Если организации в сессии нет, предотвращаем утечку данных
// Возвращаем условие, которое всегда ложно
if (empty($orgId)) {
return $this->where('1=0');
}
// Имя поля с organization_id (можно переопределить в модели)
$field = $this->table . '.organization_id';
return $this->where($field, $orgId);
}
/**
* Проверяет, что запись принадлежит текущей организации.
*
* @param int $id ID записи
* @return bool
*/
public function belongsToCurrentOrg(int $id): bool
{
return $this->forCurrentOrg()->find($id) !== null;
}
}