count系、updatedAt系のカラムはトリガーで更新するようにしたい
Summary
アプリケーションサイドでやるとCASCADE削除とかに対応できないし処理的にも無駄なため ただTypeORMでは現在migrationに直接SQL書く以外でトリガーの定義はサポートされていない https://github.com/typeorm/typeorm/issues/1082
Translation for those who find this :)
If you do it on the application side, you can not deal with CASCADE deletion and it is useless in terms of processing However, TypeORM does not currently support the definition of triggers other than writing SQL directly in migration.
しょうがないから生SQL書くかしら
こんな感じか
CREATE FUNCTION user_update_notes_count() RETURNS trigger AS $body$
BEGIN
IF (TG_OP = 'INSERT') THEN
UPDATE "user" SET "notesCount" = "notesCount" + 1 WHERE "user"."id" = NEW."userId";
RETURN NEW;
ELSE
UPDATE "user" SET "notesCount" = "notesCount" - 1 WHERE "user"."id" = OLD."userId";
RETURN OLD;
END IF;
END;
$body$
LANGUAGE plpgsql;
CREATE TRIGGER user_update_notes_count_trigger AFTER INSERT OR DELETE ON "note" FOR EACH ROW
EXECUTE FUNCTION user_update_notes_count();
ローカルで動作確認
それだと結局CASCADE削除とかに対応できてなくない?
もちろんdelete分も作る
あーCASCADEでdeleteされるレコードはトリガ発火しないとかそういうこと?