或用于TAX_QUERY中的单个分类

时间:2021-04-25 作者:Rando Hinn

我有一个tax_query 具有如下附加值:

$query->query_vars[\'tax_query\'][] = array(
    \'taxonomy\' => \'location\',
    \'include_children\' => true,
    \'field\' => \'county\',
    \'terms\' => array($_REQUEST[\'s-location\']),
    \'operator\' => \'IN\'
);
现在我想把这个作为OR 以上内容。的总体关系tax_query 仍然需要AND, 但我希望这个分类法OR 介于两者之间。我怎样才能做到这一点?

$query->query_vars[\'tax_query\'][] = array(
    \'taxonomy\' => \'location\',
    \'include_children\' => true,
    \'field\' => "JSON_EXTRACT(ads_value, \'$.paadress\')",
    \'terms\' => \'%\'.$cname.\'%\',
    \'operator\' => \'LIKE\'
);

1 个回复
最合适的回答,由SO网友:Sally CJ 整理而成

所以你在评论中说:

我们正在进行地址系统迁移,这个查询需要返回其中一个匹配的对象。要么oldsystem(county字段)设置为id,要么address值与搜索词匹配

如果你看看documentation, 自定义术语字段,如countyads_value (或JSON_EXTRACT()) 在您的情况下,不支持LIKE 也不是的标准值operator; 然而,既然你说过<是的,它们单独工作“;,那么让我们假设您有一些处理这些自定义字段和运算符的自定义代码?

我认为你所需要做的就是把这两个条件/条款放在一个单独的条款中OR 这样的关系:

$tax_query = (array) ( $query->query_vars[\'tax_query\'] ?? array() );

// Add a (named) top-level clause with an OR relation.
$tax_query[\'location\'] = array(
    \'relation\' => \'OR\',
);

// Sub-clause 1: Search in the \'county\' field.
// *You should check if $_REQUEST[\'s-location\'] is set.
$tax_query[\'location\'][] = array(
    \'taxonomy\'         => \'location\',
    \'include_children\' => true,
    \'field\'            => \'county\',
    \'terms\'            => array( $_REQUEST[\'s-location\'] ),
    \'operator\'         => \'IN\',
);

// Sub-clause 2: Search in the ads_value field.
$tax_query[\'location\'][] = array(
    \'taxonomy\'         => \'location\',
    \'include_children\' => true,
    \'field\'            => "JSON_EXTRACT(ads_value, \'$.paadress\')",
    \'terms\'            => \'%\' . $cname . \'%\',
    \'operator\'         => \'LIKE\',
);

$query->query_vars[\'tax_query\'] = $tax_query;

/* Or short version:
$query->query_vars[\'tax_query\'][] = array(
    \'relation\' => \'OR\',

    // sub-clause 1
    array(
        \'taxonomy\' => \'location\',
        \'field\'    => \'county\',
        \'terms\'    => array( $_REQUEST[\'s-location\'] ),
        \'operator\' => \'IN\',

    ),

    // sub-clause 2
    array(
        \'taxonomy\' => \'location\',
        \'field\'    => "JSON_EXTRACT(ads_value, \'$.paadress\')",
        \'terms\'    => \'%\' . $cname . \'%\',
        \'operator\' => \'LIKE\',
    ),
);
*/
还是我弄错了?如果是,请告诉我,我会相应地调整我的答案。

相关推荐