Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
588 views
in Technique[技术] by (71.8m points)

egg-sequelize+typescript一对一关联查询错误

这里我创建了两张表,一张是文章表,一张是文章类型表
文章表model

// app/model/Article.ts
import { Application } from 'egg';

export default function(app: Application) {
  const { INTEGER, STRING } = app.Sequelize;
  const Article = app.model.define('article', {
    id: {
      type: INTEGER,
      primaryKey: true,
      autoIncrement: true,
    },
    title: STRING(255),
    case_id: INTEGER,
  }, {
    timestamps: false, // 去除createAt updateAt
    freezeTableName: true, // 使用自定义表名
  });

  return class extends Article {
    static associate() {
      app.model.Article.belongsTo(app.model.Case, { foreignKey: 'case_id', targetKey: 'id' });
    }
  };
}

文章类型表model

import { Application } from 'egg';

export default function(app: Application) {
  const { INTEGER, STRING } = app.Sequelize;
  const Case = app.model.define('case', {
    id: {
      type: INTEGER,
      primaryKey: true,
      autoIncrement: true,
    },
    value: STRING(255),
  }, {
    timestamps: false, // 去除createAt updateAt
    freezeTableName: true, // 使用自定义表名
  });

  return class extends Case {};
}

我在文章类型表中写试过这样写的

return class extends Case {
    static associate() {
      app.model.Case.hasMany(app.model.Article, { as: 'articles' });
    }
  };

虽然我感觉不用加这个 hasMany,因为我这个只是一对一,在文章表中我已经使用 belongsTo 进行关联了,只是官方demo是这样写的,但是还是会报错,报错信息如下:
image.png
里面的sql语句是这个

SELECT ``.`id`, ``.`title`, ``.`case_id`, `case`.`id` AS `case.id` FROM `article` AS `` LEFT OUTER JOIN `case` AS `case` ON ``.`case_id` = `case`.`id`;

我试了下

SELECT
    `article`.`id`,
    `article`.`title`,
    `article`.`case_id`,
    `case`.`id` AS `case.id` 
FROM
    `article` AS `article`
    LEFT OUTER JOIN `case` AS `case` ON ``.`case_id` = `case`.`id`;

要这么写才会出现结果,有大佬知道在belongsTo中该怎么写才能给表重命名呢,不是给关联的表case重命名,这个用 as 就可以重命名了,是给 article 重命名

看错误信息是两个表都有 id 字段,当连接的时候会出现列重复,这种在mysql里面很好解决,直接指定显示哪个表的id就好,但是在代码里面有点懵逼,希望有大佬能帮帮我

数据库表

case表
image.png
article表
image.png


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神解答

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...