| 49 | |
| 50 | == Приказ на сите дискусии во рамки на даден topic, подредени според формула за популарност |
| 51 | |
| 52 | {{{ |
| 53 | WITH RECURSIVE tree AS ( |
| 54 | SELECT |
| 55 | t.id, |
| 56 | content, |
| 57 | created_at, |
| 58 | t.is_created_by, |
| 59 | 0::numeric as "level", |
| 60 | -1 as "parent" |
| 61 | FROM topic_thread tt |
| 62 | join thread t |
| 63 | on t.id = tt.id |
| 64 | where t.id = :topicId |
| 65 | |
| 66 | UNION ALL |
| 67 | |
| 68 | SELECT child.id, |
| 69 | child.content, |
| 70 | child.created_at, |
| 71 | child.is_created_by, |
| 72 | parent.level+1 as level, |
| 73 | dt.contained_in as parent |
| 74 | FROM thread child |
| 75 | join discussion_thread dt |
| 76 | on child.id = dt.id |
| 77 | JOIN tree parent |
| 78 | ON dt.contained_in = parent.id |
| 79 | ), |
| 80 | thread_data as (SELECT tc.id as "id", |
| 81 | tc.content as "content", |
| 82 | tc.created_at as "created_at", |
| 83 | tc.level as "level", |
| 84 | tc.parent as "parent_id", |
| 85 | u.id as userId, |
| 86 | u.username, |
| 87 | (SELECT COUNT(*) |
| 88 | FROM tree row |
| 89 | WHERE |
| 90 | tc.id = |
| 91 | row.parent) AS numReplies, |
| 92 | (SELECT COALESCE( |
| 93 | array_agg(l.user_id), |
| 94 | '{}') |
| 95 | FROM likes l |
| 96 | WHERE |
| 97 | l.thread_id = |
| 98 | tc.id) AS likedByUserIds |
| 99 | FROM tree tc |
| 100 | join users u |
| 101 | on u.id = |
| 102 | tc.is_created_by) |
| 103 | SELECT |
| 104 | id, |
| 105 | content, |
| 106 | created_at as createdAt, |
| 107 | level, |
| 108 | parent_id as parentId, |
| 109 | userId, |
| 110 | username, |
| 111 | numReplies, |
| 112 | likedByUserIds |
| 113 | FROM thread_data td |
| 114 | ORDER BY |
| 115 | level, |
| 116 | 0.3 * numReplies + 0.7 * cardinality(likedByUserIds) |
| 117 | DESC ; |
| 118 | }}} |
| 119 | |
| 120 | * Прашаликот за секој discussion ги враќа user_id што поставиле like како низа, со цел да може потоа во апликацијата да се прикаже точно кој корисник поставил like. |