OwnedByAgentAccount.php 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. <?php
  2. namespace App\Models\Concerns;
  3. use App\Services\V3\AgentAccount;
  4. use Illuminate\Contracts\Database\Eloquent\Builder;
  5. /**
  6. * 带 `account_type` + `account_id` 两列(AI 对话 / 积分的账号)的模型。
  7. *
  8. * 按账号查询只准用 {@see scopeOwnedBy()}:两列一起比,游客把设备 id 填成某个用户的 uid 也冒充不了他。
  9. *
  10. * @property string $account_type user / guest
  11. * @property string $account_id 用户 uuid 或设备匿名 uuid
  12. */
  13. trait OwnedByAgentAccount
  14. {
  15. public function scopeOwnedBy(Builder $query, AgentAccount $account): void
  16. {
  17. $query->where($this->qualifyColumn('account_type'), $account->type)
  18. ->where($this->qualifyColumn('account_id'), $account->id);
  19. }
  20. public function isOwnedBy(AgentAccount $account): bool
  21. {
  22. return $this->account_type === $account->type && $this->account_id === $account->id;
  23. }
  24. /**
  25. * 这一行的账号。
  26. */
  27. public function account(): AgentAccount
  28. {
  29. return $this->account_type === 'user'
  30. ? AgentAccount::user($this->account_id)
  31. : AgentAccount::guest($this->account_id);
  32. }
  33. }