条件(三元)运算符未按预期运行(Javascript)

时间:2018-12-31 23:46:21

标签: javascript neo4j conditional-statements

我有这种情况,我希望看到基于userIdname的结果(如果userId是基于userId提出的搜索,而名字是基于else提出的搜索的名字),但我收到的是总是返回userId而没有考虑function findUsers(userId, name, skip, limit) { let queryString = (userId) ? 'MATCH (user:User {userId:{userId}}) ' : 'MATCH (user:User) ' + 'WHERE ((user.username =~ {name}) OR (user.name =~ {name})) ' + 'WITH user ' + 'ORDER BY user.name ' + 'RETURN DISTINCT user.userId, user.username, user.name ' + 'SKIP {skip} LIMIT {limit}'; let cypher = { query: queryString, params: { userId: userId, name: util.format('(?i).*%s.*', name), skip: skip, limit: limit } };

class Token(val original: TokenPattern)

1 个答案:

答案 0 :(得分:1)

三元组的优先级比+低,因此所有串联都放在else部分中。使用括号,以便您根据三元选择合适的MATCH选项。

  let queryString = (
        (userId) ?
        'MATCH (user:User {userId:{userId}}) ' :
        'MATCH (user:User) ') +
    'WHERE ((user.username =~ {name}) OR (user.name =~ {name})) ' +
    'WITH user ' +
    'ORDER BY user.name ' +
    'RETURN DISTINCT user.userId, user.username, user.name ' +
    'SKIP {skip} LIMIT {limit}';

您甚至可以进一步缩小范围:

  let queryString = 'MATCH (user:User ' + (userId ? '{userId:{userId}}' : '') + ') ' +
    'WHERE ((user.username =~ {name}) OR (user.name =~ {name})) ' +
    'WITH user ' +
    'ORDER BY user.name ' +
    'RETURN DISTINCT user.userId, user.username, user.name ' +
    'SKIP {skip} LIMIT {limit}';