如何在Sequelize中使用ON子句中的多个谓词进行LEFT JOIN?

laz*_*uly 2 postgresql orm node.js sequelize.js

这是我非常简单的Sequelize模型关系:

    models["Post"]
        .hasMany(models["PostLike"])
    models["PostLike"]
        .belongsTo(models["Post"])
Run Code Online (Sandbox Code Playgroud)

这是我的Sequelize.findAll查询(用CoffeeScript编写):

Post.findAll
            include : [ PostLike ]
            where : where
            offset : start
            limit : limit
            order : order
.success (posts) =>
     ......
.failure (error) =>
     ......
Run Code Online (Sandbox Code Playgroud)

如你所见,我包括PostLike模型,Sequelize产生正确的LEFT JOIN:

...FROM "posts" LEFT JOIN "post_likes" AS "post_likes" 
    ON "posts"."id" = "posts_likes"."post_id" ...
Run Code Online (Sandbox Code Playgroud)

但是,我想让Sequelize使用我的自定义标准扩展ON谓词:

... ON "posts"."id" = "posts_likes"."post_id" AND posts_likes.author_id = 123
Run Code Online (Sandbox Code Playgroud)

这可能是非常容易的事情,我在文档中找不到它.

谢谢

Ben*_*une 10

请原谅缺乏CoffeeScript,但你可以这样做:

Post.findAll({
    include: [{
        model: PostLike,
        where: { author_id: 123 }
    }]
})
Run Code Online (Sandbox Code Playgroud)

我在代码中发现了以下注释,这些注释也可能有用.

* @param  {Array<Object|Model>}       [options.include] A list of associations to eagerly load using a left join. Supported is either `{ include: [ Model1, Model2, ...]}` or `{ include: [{ model: Model1, as: 'Alias' }]}`. If your association are set up with an `as` (eg. `X.hasMany(Y, { as: 'Z }`, you need to specify Z in the as attribute when eager loading Y).
   * @param  {Model}                     [options.include[].model] The model you want to eagerly load
   * @param  {String}                    [options.include[].as] The alias of the relation, in case the model you want to eagerly load is aliassed. For `hasOne` / `belongsTo`, this should be the singular name, and for `hasMany`, it should be the plural
   * @param  {Association}               [options.include[].association] The association you want to eagerly load. (This can be used instead of providing a model/as pair)
   * @param  {Object}                    [options.include[].where] Where clauses to apply to the child models. Note that this converts the eager load to an inner join, unless you explicitly set `required: false`
   * @param  {Array<String>}             [options.include[].attributes] A list of attributes to select from the child model
   * @param  {Boolean}                   [options.include[].required] If true, converts to an inner join, which means that the parent model will only be loaded if it has any matching children. True if `include.where` is set, false otherwise.
   * @param  {Array<Object|Model>}       [options.include[].include] Load further nested related models
Run Code Online (Sandbox Code Playgroud)

  • 关于"对内连接的热切加载,请注意,除非您明确设置`required:false`"有很多帮助.谢谢! (10认同)