我希望能够从SQL Server返回一个ids的JSON数组作为JSON对象的一部分。
我试图使它起作用并接近,但这不是我想要构造JSON的方式。
此SQL我已经输出了
add_action( 'woocommerce_cart_calculate_fees', 'add_discount_line' );
function add_discount_line( $cart ) {
if($cart->get_applied_coupons() && $cart->subtotal==0):
$getDetails = ( new WC_Coupon($cart->get_applied_coupons()));
$discount = $getDetails->amount;
$cart->add_fee( __( 'Special Discount', 'woocommerce' ) , -$discount );
endif;
}
这会生成具有我想要的所有内容的JSON,但我想将rigIds构建为JSON数组,以生成类似的内容,所以我不会无缘无故地复制对象。
SELECT c.Pk_Company_Id AS [id],
c.Name AS [name],
r.Pk_Rig_Id AS [rigId]
FROM Company c
LEFT JOIN Rig r
ON c.Pk_Company_Id = r.Fk_Company_Id
FOR JSON PATH, ROOT('companies')
{"companies":[{"id":1,"name":"Company 1","rigId":100},{"id":1,"name":"Company 1","rigId":101},{"id":2,"name":"Company 2"}]}
答案 0 :(得分:1)
带有REPLACE
的变体:
SELECT
c.Pk_Company_Id AS [id],
c.Name AS [name],
JSON_QUERY(REPLACE(REPLACE((SELECT r.Pk_Rig_Id id FROM Rig r WHERE c.Pk_Company_Id = r.Fk_Company_Id FOR JSON PATH),'{"id":',''),'}','')) [rigIds]
FROM Company c
FOR JSON PATH, ROOT('companies')
-- {"companies":[{"id":1,"name":"Company 1","rigIds":[100,101]},{"id":2,"name":"Company 2"}]}
带有STRING_AGG
的变体:
SELECT
c.Pk_Company_Id AS [id],
c.Name AS [name],
JSON_QUERY((SELECT '['+STRING_AGG(r.Pk_Rig_Id,',')+']' FROM Rig r WHERE c.Pk_Company_Id = r.Fk_Company_Id)) [rigIds]
FROM Company c
FOR JSON PATH, ROOT('companies')