2017-09-12 1 views
0

나는 하나의 관계가 많은 order_productsorder_product_tax 두 테이블이 있습니다. 하나 order_products 여러 order_product_tax 여기MySQL 테이블 by 및 왼쪽 연결된 테이블에 PHP Yii2

두 테이블 나는이

[ 
{ 
    "product_id":2809, 
    "product_name":"Test Product1", 
    "quantity":5, 
    "amount":500, 
    "taxes":[ 
    { 
     "tax_id":47, 
     "tax_name":"VAT", 
     "tax_amount":21.14 
    }, 
    { 
     "tax_id":48, 
     "tax_name":"CST", 
     "tax_amount":5.17 
    } 
    ] 
}, 
{ 
    "product_id":2810, 
    "product_name":"Test Product2", 
    "quantity":4, 
    "amount":200, 
    "taxes":[ 
    { 
     "tax_id":47, 
     "tax_name":"VAT", 
     "tax_amount":12.57 
    }, 
    { 
     "tax_id":48, 
     "tax_name":"CST", 
     "tax_amount":11.34 
    } 
    ] 
} 
] 

같은 출력이 나는이 결과를 얻을 수있는 방법을 얻을 필요가 http://sqlfiddle.com/#!9/2608e

에 대한 SQL 바이올린이있을 수 있습니까?

저는 PHP와 Yii2를 사용하고 있습니다.

도움이 될 것입니다.

편집 : Yii2 모델

OrderProduct

OrderProductTax

class OrderProductTax extends \yii\db\ActiveRecord 
{ 

    public static function tableName() 
    { 
    return 'order_product_tax'; 
    } 

    public function rules() 
    { 
    return [ 
     [['order_product_id', 'tax_id'], 'integer'], 
     [['tax_amount'], 'number'], 
     [['tax_name'], 'string', 'max' => 20], 
    ]; 
    } 

    public function attributeLabels() 
    { 
    return [ 
     'id' => 'ID', 
     'order_product_id' => 'Order Product ID', 
     'tax_id' => 'Tax ID', 
     'tax_name' => 'Tax Name', 
     'tax_amount' => 'Tax Amount', 
    ]; 
    } 
} 
+0

order_products 테이블의 외래 키 란 무엇입니까? –

+0

@ 존 Ekiz 당신이 테이블 피들을 보면 두 테이블에 대한 자동 증분 인 'id'필드가 있습니다. –

+1

지금까지 시도한 것은 무엇입니까? –

답변

1

다음은 SQL이다. 그룹 연결을 사용하여 열을 json으로 결합 할 수 있습니다.

SELECT amounts.* 
    ,GROUP_CONCAT(CONCAT('{tax_id:"', tax_id, '", tax_name:"',tax_name,'", tax_amount:"',tax_amount,'"}')) 
FROM 
(
SELECT op.product_id, 
op.product_name, 
SUM(op.amount) as amount, 
SUM(op.quantity) as quantity 
FROM order_product op 
group by 1,2 
)amounts 
LEFT JOIN 
(
select product_id 
,tax_id 
,tax_name 
,sum(tax_amount) as tax_amount 
from order_product op 
join ordeR_product_tax opt 
on op.id = opt.order_producT_id 
group by 1,2,3 
) taxes 
on amounts.product_id = taxes.product_id 
group by 1,2,3,4 
+0

고맙습니다 .Jon Ekiz –