在yii2

时间:2016-05-04 12:59:41

标签: yii2

我有两张桌子 - 派对,账单。在聚会表中,fiels是parties_partyname,parties_district。在账单表中,它有字段bill_partyname,billamount,billdate。 我希望将查询视为

SELECT parties_district,parties_partyname, COALESCE(sum(bills.billamount),0) as sale FROM `parties` left join bills on parties.parties_partyname = bills.bills_partyname group by parties.parties_partyname

我的搜索模型看起来像 -

$query = Parties::find()
        ->select('parties.parties_district, parties.parties_partyname, bills.billamount as sale')
        ->from('parties')
        ->leftJoin('bills',['bills.bills_partyname' => 'parties.parties_partyname'])
        ->groupBy('parties.parties_partyname');

缔约方index.php

'parties_partyname',
        'parties_district',

    [
      'attribute' => 'sale',
      'value' => 'sale'
    ],

我在派对模型中添加了public $sale

1 个答案:

答案 0 :(得分:1)

如果你想使用你所展示的activeQuery,你应该使用

$query = Parties::find()
    ->select('parties.parties_district as parties_district, 
         parties.parties_partyname as parties_partyname, 
         COALESCE(sum(bills.billamount),0) as sale ')
    ->from('parties')
    ->leftJoin('bills',['bills.bills_partyname' => 'parties.parties_partyname'])
    ->groupBy('parties.parties_partyname');

否则你可以使用一个简单的(activeRecord)findBySql()(这会给你dataProvider的查询)

    $sql = 'SELECT 
                parties.parties_district as parties_district, 
                parties.parties_partyname as parties_partyname, 
                COALESCE(sum(bills.billamount),0) as sale 
            FROM `parties` 
            left join bills on parties.parties_partyname = bills.bills_partyname 
            group by parties.parties_partyname'
    $query = Parties::findBySql($sql);

如果你使用

    $models = Parties::findBySql($sql)>all();

你得到所有的模型

对于网格视图,如果您的值与属性值相同,则使用

    'parties_partyname',
    'parties_district',
    'sale', 

没有值=>