【问题标题】:Sequelize Join table1 with table[X] referenced in table1.columnSequelize Join table1 与 table1.column 中引用的 table[X]
【发布时间】:2018-11-27 21:54:30
【问题描述】:

所以我有:

  • table1=车辆
  • table2=汽车
  • table3=摩托车
  • table4=卡车...

在表 1 中,我有一个列 type 引用了上述表中的第一个表(表 2 | 表 3 | 表 4 ...)。我想列出表1中的所有车辆并加入type中引用的表;但我发现这有点困难,我发现的唯一方法是获取所有车辆并循环遍历所有车辆,并从type 中指定的相应表中获取补充数据。

例如:

车辆:

id(0)------------type(1)---------------name(dacia)

id(1)------------type(2)---------------name(porsche)

id(2)------------type(2)---------------name(hummer)

id(3)------------type(3)---------------name(kongo)

id(4)------------type(3)---------------name(renault)

汽车(类型 1):

id(0)----------vehicleId(0)-------otherInfo(new)

卡车(类型 2):

id(0)----------vehicleId(1)-------otherInfo(used)

id(1)----------vehicleId(2)-------otherInfo(like_new)

摩托车(3 型):

id(0)----------vehicleId(3)-------otherInfo(old)

id(1)----------vehicleId(4)-------otherInfo(very_old)

查询结果:

id(0)------------type(1)---------------name(dacia)-------otherInfo(new)

id(1)------------type(2)---------------name(porsche)-------otherInfo(used)

id(2)------------type(2)---------------name(hummer)-------otherInfo(like_new)

id(3)------------type(3)---------------name(kongo)-------otherInfo(old)

id(4)------------type(3)---------------name(renault)-------otherInfo(very_old)

【问题讨论】:

    标签: mysql sql node.js sequelize.js


    【解决方案1】:

    您可以使用包含车辆类型条件的 LEFT JOIN 子句,然后使用 CONCAT/COALESCE 返回(唯一)匹配值,如下所示:

    select
        v.id,
        v.type,
        v.name,
        concat( 
            coalesce( c.otherInfo, ''), 
            coalesce( t.otherInfo, ''), 
            coalesce( m.otherInfo, '') 
        ) as otherInfo
    from vehicules v
    left join cars      c on c.vehiculeId = v.id and v.type = 1
    left join trucks    t on t.vehiculeId = v.id and v.type = 2
    left join motocycle m on m.vehiculeId = v.id and v.type = 3
    

    【讨论】:

      【解决方案2】:

      我认为您需要先阅读以下内容:Associations

      这就是你如何定义两个模型/表格之间的关系,比如

      • 属于
      • 属于多方
      • 有一个
      • 有很多

      完成此操作后,您可以查询模型以获取所需的真实数据。例子

      // Find all projects with a least one task where task.state === project.state
      Project.findAll({
          include: [{
              model: Task
              // you can go nested too , as per your requirment        
          }]
      })
      

      这是你在使用 sequelize.js 时应该做的事情

      【讨论】:

      • 是的,这就是我所做的,这里唯一的问题是我应该包含的模型取决于 type 的值
      猜你喜欢
      • 1970-01-01
      • 2023-02-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-13
      • 2011-05-09
      • 1970-01-01
      相关资源
      最近更新 更多