如何在where子句中使用带有可选include的运算符?

hen*_*enk 5 mysql sequelize.js

我有以下型号:

AuthorModel.hasMany(BookModel);
BookModel.belongsTo(AuthorModel);
Run Code Online (Sandbox Code Playgroud)

有些作者没有书.

我想选择一个作者,他的一本书的名字或头衔与搜索字符串相匹配.

我可以通过以下声明来实现这一点,但仅限于在BookModel中拥有书籍的作者

       Author.findOne({
         include: [{
            model: Book,
            where: {
              [Op.or]: [
                  {'$author.name$': 'search string'},
                  { title: 'search string'}
                 ]
               },
             }]
           })
Run Code Online (Sandbox Code Playgroud)

这给了我或多或少的以下mysql查询:

SELECT 
    `author`.`name`,
    `book`.`title`
FROM `author` INNER JOIN `book` 
     ON `author`.`id` = `book`.`authorId`
     AND ( `author`.`name` = 'search string' OR `book`.`title` = 'search string');
Run Code Online (Sandbox Code Playgroud)

这里的问题是,如果作者没有书籍,那么结果是空的.即使有作者符合搜索条件.

我试图将include设置为required: false,给出了一个left outer join.在这种情况下,我得到一些不匹配的结果.省略了where子句.

我如何更改sequelize查询,或者什么是正确的mysql查询?

Ser*_*gGr 5

MySql 查询应该类似于

SELECT 
    `author`.`name`,
    `book`.`title`
FROM `author` LEFT JOIN `book` 
     ON `author`.`id` = `book`.`authorId`
WHERE ( `author`.`name` = 'search string' OR `book`.`title` = 'search string')
Run Code Online (Sandbox Code Playgroud)

注意这里的过滤条件是在WHERE而不是JOIN ... ON子句的一部分

基于顶级的示例,其中使用急切加载的模型,您可以查询查询应该是这样的

Author.findOne({
    where: {
          [Op.or]: [
              {'$author.name$': 'search string'},
              { '$Book.title$': 'search string'}
             ]
           },
    include: [{
        model: Book,           
        required: false
       }]})
Run Code Online (Sandbox Code Playgroud)