4

sequelize、mysql 问题求解答!一张表多个关联关系问题。

 2 years ago
source link: https://www.v2ex.com/t/792753
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

V2EX  ›  Node.js

sequelize、mysql 问题求解答!一张表多个关联关系问题。

  yishen0 · 4 小时 49 分钟前 · 157 次点击

image

Worker.hasMany(Worker_task, { foreignKey: 'worker_id' })
Worker_task.belongsTo(Worker, { foreignKey: 'worker_id', targetKey: 'id' })
Worker.hasMany(Worker_task, { foreignKey: 'other_workerid' })
Worker_task.belongsTo(Worker, { foreignKey: 'other_workerid', targetKey: 'id' })

上面是我的数据表关系。worker_task表中worker_id 字段指向worker.id,为一对多关系。

worker_task表中other_workerid字段同样指向worker.id,为一对多关系。

业务简化逻辑

员工、员工任务。员工甲委派任务给员工乙,worker_id就是甲的 id,other_workerid就是乙的 id 。

现在要通过,worker_task 表查询出,worker_id 和 other_workerid 对应的信息。下边是我的 sequelize 查询语句。

// workerId
const data = await Worker_task.findAndCountAll({
  attributes: ['worker_id', 'task_id', 'trust_relation', 'other_workerid'],
  include: [
    // TODO 现在查出来,是 other_workerid 对应的 worker 。我想把 worker_id 和 other_workerid 对应的 worker 记录都查询出来。
    { model: Worker, attributes: ['name'] },
  ],
  where: {
    [Op.or]: [
      {
        worker_id: workerId,
      },
      {
        other_workerid: workerId,
      },
    ],
  },
})

求助 sequelize 语句或者原始 mysql 语句。或者换其他可行的思路也是 ok 的,提前谢谢大家!


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK