sequelize icon indicating copy to clipboard operation
sequelize copied to clipboard

Limit not return enough with where in included belongsToMany Model (M:N)

Open khoanguyen-3fc opened this issue 10 years ago • 3 comments

What you are doing?

var Sequelize = require('sequelize');

var sequelize = new Sequelize('test', 'root', '', {
    'host': '127.0.0.1',
    'dialect': 'mysql',
    'define': {
        'timestamps': false
    }
});

var Post = sequelize.define('post');
var Category = sequelize.define('category');

Post.belongsToMany(Category, {through: 'post_category'});
Category.belongsToMany(Post, {through: 'post_category'});

sequelize.sync({
    force: true
})
    .then(() => Post.create())
    .then(p1 => [
        p1,
        Post.create(),
    ])
    // make sure that p1 created before p2, p2 before p3
    .spread((p1, p2) => [
        p1,
        p2,
        Post.create(),
        Category.create(),
        Category.create(),
    ])
    .spread((p1, p2, p3, c1, c2) => [
        c2,
        // all post have category
        c1.setPosts(p2),
        c2.setPosts([p1, p3]),
    ])
    .spread(c2 => Post.findAll({
        limit: 2,
        include: [{
            model: Category,
            where: {
                id: c2.id
            }
        }]
    }))
    .then(posts => {
        // expected 2
        console.log(posts.length);
    })
    .finally(() => sequelize.close());

What do you expect to happen?

posts.length should be 2

What is actually happening?

posts.length returned 1

Output SQL

SELECT
   `post`.*,
   `categories`.`id` AS `categories.id`,
   `categories.post_category`.`postId` AS `categories.post_category.postId`,
   `categories.post_category`.`categoryId` AS `categories.post_category.categoryId` 
FROM
   (SELECT
      `post`.`id` 
   FROM
      `posts` AS `post` 
   WHERE
      (
         SELECT
            `post_category`.`postId` 
         FROM
            `post_category` AS `post_category` 
         INNER JOIN
            `categories` AS `category` 
               ON `post_category`.`categoryId` = `category`.`id` 
         WHERE
            (
               `post`.`id` = `post_category`.`postId`
            ) LIMIT 1 
      ) IS NOT NULL LIMIT 2
   ) AS `post` 
INNER JOIN
   (
      `post_category` AS `categories.post_category` 
   INNER JOIN
      `categories` AS `categories` 
         ON `categories`.`id` = `categories.post_category`.`categoryId`
      ) 
         ON `post`.`id` = `categories.post_category`.`postId` 
         AND `categories`.`id` = 2;

Dialect: mysql Database version: 5.5.49-0ubuntu0.14.04.1 Sequelize version: 3.23.6

khoanguyen-3fc avatar Jul 21 '16 11:07 khoanguyen-3fc

When I not using limit, ouput SQL is

SELECT
   `post`.`id`,
   `categories`.`id` AS `categories.id`,
   `categories.post_category`.`postId` AS `categories.post_category.postId`,
   `categories.post_category`.`categoryId` AS `categories.post_category.categoryId` 
FROM
   `posts` AS `post` 
INNER JOIN
   (
      `post_category` AS `categories.post_category` 
   INNER JOIN
      `categories` AS `categories` 
         ON `categories`.`id` = `categories.post_category`.`categoryId`
      ) 
         ON `post`.`id` = `categories.post_category`.`postId` 
         AND `categories`.`id` = 2;

So, why there're the part

   (SELECT
      `post`.`id` 
   FROM
      `posts` AS `post` 
   WHERE
      (
         SELECT
            `post_category`.`postId` 
         FROM
            `post_category` AS `post_category` 
         INNER JOIN
            `categories` AS `category` 
               ON `post_category`.`categoryId` = `category`.`id` 
         WHERE
            (
               `post`.`id` = `post_category`.`postId`
            ) LIMIT 1 
      ) IS NOT NULL LIMIT 2
   ) AS `post` 

Not just add LIMIT x to the first SQL?

SELECT
   `post`.`id`,
   `categories`.`id` AS `categories.id`,
   `categories.post_category`.`postId` AS `categories.post_category.postId`,
   `categories.post_category`.`categoryId` AS `categories.post_category.categoryId` 
FROM
   `posts` AS `post` 
INNER JOIN
   (
      `post_category` AS `categories.post_category` 
   INNER JOIN
      `categories` AS `categories` 
         ON `categories`.`id` = `categories.post_category`.`categoryId`
      ) 
         ON `post`.`id` = `categories.post_category`.`postId` 
         AND `categories`.`id` = 2
LIMIT 2;

PS: sorry for my bad English

khoanguyen-3fc avatar Jul 29 '16 06:07 khoanguyen-3fc

I confirm this, getting same result in similar situation:

var S = require('sequelize');

var s = new S(undefined, undefined, undefined, {
  dialect: 'sqlite'
});

var item = s.define('item', {user_id: S.DataTypes.INTEGER});
var tag = s.define('tag', {name: S.DataTypes.STRING});

item.belongsToMany(tag, {through: 'item_tag'});
tag.belongsToMany(item, {through: 'item_tag'});

s.sync({force: true})
.then(() => tag.create({name: 'test1'}))
.then((t1) => [
  t1,
  tag.create({name: 'test2'}),
  item.create({user_id: 1}),
  item.create({user_id: 1})
])
.spread((t1, t2, i1, i2) => [i1.addTag(t2), i2.addTag(t1)])
.spread(() => item.findAndCountAll({
  limit: 1,
  where: { user_id: 1 },
  include: [{
    model: tag,
    where: {name: {$in: ['test1']}}
  }]
}))
.then(r => console.log(r));

Produces { count: 1, rows: [] }

Swapping t1/t2 in items, i.e.

.spread((t1, t2, i1, i2) => [i1.addTag(t1), i2.addTag(t2)])

produces correct result like

{ count: 1,
  rows: 
   [ Instance {
       dataValues: [Object],
       _previousDataValues: [Object],
       _changed: {},
       '$modelOptions': [Object],
       '$options': [Object],
       hasPrimaryKeys: true,
       __eagerlyLoadedAssociations: [],
       isNewRecord: false,
       tags: [Object] } ] }```

syadykin avatar Jan 30 '17 22:01 syadykin

Does anybody work on this? I see the same issue for Database version: 5.7 Sequelize version: 4.0.0-2

natanik avatar Apr 03 '17 08:04 natanik