# Невозможно автоматически добавить пользователя в группу в анонимном режиме

**URL:** <https://meta.discourse.org/t/cant-add-user-in-anonymous-mode-to-a-group-automatically/166151>\
**Category:** Feature\
**Tags:** anonymous-mode\
**Created:** [04.Октябрь.2020 01:33:58 UTC](https://meta.discourse.org/t/cant-add-user-in-anonymous-mode-to-a-group-automatically/166151 "2020-10-04T01:33:58Z")\
**Posts on this page:** 1\
**Showing post:** 8

<div class="post-metadata">

**Author:** ![steinhh](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/steinhh/32/242776_2.png) [@steinhh](https://meta.discourse.org/u/steinhh)\
**Post date:** [31.Август.2023 08:36:29 UTC](https://meta.discourse.org/t/cant-add-user-in-anonymous-mode-to-a-group-automatically/166151/8 "2023-08-31T08:36:29Z")

</div>

Кстати, я «решал» эту проблему на уровне базы данных в форуме, который я веду. Используйте этот подход только в том случае, если не удаётся применить другие, более высокоуровневые решения (есть ли какие-то прогресс в этом вопросе или следует пометить один из существующих ответов как «решённый»)? Вот код для PostgreSQL:

```plaintext
create or replace function anon_insert_copy_groups_to_anon_user()
  RETURNS TRIGGER 
  LANGUAGE PLPGSQL
  AS $$
declare
  anon_user_id integer = new.user_id;
  master_user_id integer = new.master_user_id;
  active boolean = new.active;
  created_at timestamp = new.created_at;
  updated_at timestamp = new.updated_at;
BEGIN
  insert into group_users 
        (group_id, user_id, created_at, updated_at, owner, notification_level, first_unread_pm_at)
  select group_users.group_id, anon_user_id , current_timestamp, current_timestamp, false, 3 as notification_level, current_timestamp
  from group_users 
  where group_users.user_id=master_user_id
  and group_users.group_id not in (select group_id from group_users where group_users.user_id=anon_user_id)
  and group_users.group_id not in (1, 2, 3); -- исключаем администраторов, модераторов и персонал!

  return new;
end;
$$;

-- Создание триггера
CREATE TRIGGER anon_insert_trigger
AFTER INSERT ON anonymous_users
  FOR EACH ROW
    EXECUTE FUNCTION anon_insert_copy_groups_to_anon_user();

```

---

_[View the full topic](https://meta.discourse.org/t/cant-add-user-in-anonymous-mode-to-a-group-automatically/166151)._
