我在Yii2中创建了一个API,其中包含以下查询:
public function actionGetcarinfo($ac, $id){
Yii::$app->response->format = Response::FORMAT_JSON;
$rows = (new Query())
->select(['a.auto_id', 'm.merk', 'a.model', 'a.uitvoering', 'k.kleur', 't.transmissie', 'a.kmstand', 'a.bouwjaar', 'a.vermogen', 'b.brandstof', 'g.garantie', 'a.prijs'])
->from('auto_new a')
->where(['a.ac' => $ac, 'a.auto_id' => $id])
->join('INNER JOIN', 'tbl_merken m', 'a.merk = m.merk_id')
->join('INNER JOIN', 'tbl_kleur k', 'a.kleur = k.kleur_id')
->join('INNER JOIN', 'tbl_transmissie t', 'a.transmissie = t.transmissie_id')
->join('INNER JOIN', 'tbl_brandstof b', 'a.brandstof = b.brandstof_id')
->join('INNER JOIN', 'tbl_garantie g', 'a.garantie = g.garantie_id')
->all();
return $rows;
}
而且:
public function actionGetcaroptions($ac, $id){
Yii::$app->response->format = Response::FORMAT_JSON;
$rows = (new Query())
->select(['atn.NL'])
->from('auto_new a')
->where(['a.ac' => $ac, 'a.auto_id' => $id])
->join('INNER JOIN', 'auto_accessoire acc', 'a.auto_id = acc.auto_id AND a.ac = acc.ac')
->join('INNER JOIN', 'tbl_accessoires_trader_new atn', 'acc.code_id = atn.code_id')
->all();
return $rows;
}
现在我想在上面的查询中添加带有选项的列表。所以json会得到类似:options:list with options。
我不知道如何将这两个查询一起添加。
答案 0 :(得分:1)
在普通的旧sql中,您的查询是:
select a.auto_id, m.merk, a.model, a.uitvoering, k.kleur, t.transmissie, a.kmstand, a.bouwjaar, a.vermogen, b.brandstof, g.garantie, a.prijs
from auto_new a
INNER JOIN tbl_merken m on a.merk = m.merk_id
INNER JOIN tbl_kleur k on a.kleur = k.kleur_id
INNER JOIN tbl_transmissie t on a.transmissie = t.transmissie_id
INNER JOIN tbl_brandstof b on a.brandstof = b.brandstof_id
INNER JOIN tbl_garantie g on a.garantie = g.garantie_id
WHERE a.ac = ? and a.auto_id = ?
select atn.NL
from auto_new a
INNER JOIN auto_accessoire acc on a.auto_id = acc.auto_id AND a.ac = acc.ac
INNER JOIN tbl_accessoires_trader_new atn on acc.code_id = atn.code_id
WHERE a.ac = ? and a.auto_id = ?
结合这些
select a.auto_id, m.merk, a.model, a.uitvoering, k.kleur, t.transmissie, a.kmstand, a.bouwjaar, a.vermogen, b.brandstof, g.garantie, a.prijs,
group_concat(atn.NL) as options_list
from auto_new a
INNER JOIN tbl_merken m on a.merk = m.merk_id
INNER JOIN tbl_kleur k on a.kleur = k.kleur_id
INNER JOIN tbl_transmissie t on a.transmissie = t.transmissie_id
INNER JOIN tbl_brandstof b on a.brandstof = b.brandstof_id
INNER JOIN tbl_garantie g on a.garantie = g.garantie_id
INNER JOIN auto_accessoire acc on a.auto_id = acc.auto_id AND a.ac = acc.ac
INNER JOIN tbl_accessoires_trader_new atn on acc.code_id = atn.code_id
WHERE a.ac = ? and a.auto_id = ?
group by a.auto_id, m.merk, a.model, a.uitvoering, k.kleur, t.transmissie, a.kmstand, a.bouwjaar, a.vermogen, b.brandstof, g.garantie, a.prijs
有关详细信息,请参阅http://dev.mysql.com/doc/refman/5.7/en/group-by-functions.html。逻辑只是将两个查询与连接一起添加,然后获取选项行并将它们组成一个字符串(因此每个a.ac和a.auto_id都有一行所有选项)。希望有所帮助。