top-think / think-orm

Think ORM——the PHP Database&ORM Framework
Apache License 2.0
416 stars 173 forks source link

MongoDB下查询中包含数组/对象时自动加 $in 的问题。 #513

Open CNBroderick opened 10 months ago

CNBroderick commented 10 months ago

使用版本:

{ 
  "topthink/think-orm": "^3.0"
}

争议代码位置: src/db/concern/WhereQuery.php:parseArrayWhereItems#504

当以此代码作为查询条件时:

$where = [
    'time' => [
        '$gte' => 1703508340 * 1000000000,
        '$lt' => (1703508340 + 1) * 1000000000,
    ],
    'ip' => [
        '$in' => [
            '123.123.123.123',
            '1.1.1.1',
            '2.2.2.2',
        ]
    ]
];
(new UserLoginLog())->where($where)->field('_id')->failException()->find();

实际的查询条件为:

db.user_login_log
  .find({
    $and: [
      {
        time: {
          $in: { $gte: 1703508340000000000, $lt: 1703508341000000000 },
        },
      },
      {
        time: {
          $in: { $in: ["123.123.123.123", "1.1.1.1", "2.2.2.2"] },
        },
      },
    ],
  })
  .limit(1);

咨询: 是否有一个方法,可以像ThinkPHP 3.2.3时的MongoModel中的写法,将以上的查询条件直接进行 json_encode操作呢?

CNBroderick commented 10 months ago

当前找到的解决方法是将array强转成object,这个办法是否是推荐写法?如果是可以加到文档中吗?

$where = [
    'time' => (object) [
        '$gte' => 1703508340 * 1000000000,
        '$lt' => (1703508340 + 1) * 1000000000,
    ],
    'ip' => [
        '$in' => (object) [
            '123.123.123.123',
            '1.1.1.1',
            '2.2.2.2',
        ]
    ]
];