【问题标题】:reverse relation in postgrespostgres中的反向关系
【发布时间】:2021-06-29 23:47:58
【问题描述】:

我的数据库“textDate”中有表格

class TextData extends BaseEntity{
 
id(primaryGeneratedColumn)

ar:string

en:string

}

此实体用于存储我的项目中的所有文本,如标题、描述和其他字段都有外键

class object extends baseEntity{

id

@OneToOne()
@joinColumn()
title:TextData
...

由于某些条件,我需要在文本数据中搜索并从中获取记录,并且我想获取对该 textData 记录具有 Fk 的对象 注意:有几种类型的对象可以访问文本数据 object1(title),car(title),career(title) 他们都有fk到文本数据...... 有什么事情要做吗? 我做了

 select 'post' as Type,p3 .id 
from post p3  
where p3."tagsId" =any ('{1,2,3}') or p3."titleId" =any ('{1,2,3}') 
 join text_data td 
 on td.id =p3."titleId" as  titil
UNION  
select 'career' as Type,c2 .id 
from career c2 
join text_data td 
 on td.id =c2."titleId" as  titil
where c2."tagsId" =any ('{1,2,3}')

【问题讨论】:

    标签: typescript postgresql reverse typeorm


    【解决方案1】:

    您可以在 text_data 中保存对子表的引用,例如子表的名称。

    您的查询有一些错误:

    select 'post' as Type, p3.id 
    from post p3  
    join text_data td on td.id = p3."titleId"
    where p3."tagsId" = any('{1,2,3}') or p3."titleId" = any('{1,2,3}')
    
    UNION  
    
    select 'career' as Type, c2.id 
    from career c2 
    join text_data td on td.id = c2."titleId" 
    where c2."tagsId" = any('{1,2,3}')
    

    另一种查询方式:

    SELECT td.id, coalesce(p3.type, c2.type) AS type
    
    FROM text_data td
    
    INNER JOIN (SELECT "titleId", 'post' AS type FROM post WHERE "tagsId" = any('{1,2,3}') or "titleId" = any('{1,2,3}')) AS p3 ON td.id = p3."titleId"
    
    INNER JOIN (SELECT "titleId", 'career' AS type FROM career WHERE "tagsId" = any('{1,2,3}')) AS c2 ON td.id = c2."titleId"
    

    【讨论】:

      猜你喜欢
      • 2018-07-05
      • 2020-09-10
      • 2014-05-27
      • 1970-01-01
      • 2023-03-10
      • 2014-05-24
      • 1970-01-01
      • 2012-07-09
      • 2012-11-03
      相关资源
      最近更新 更多