Getting (not set) when joining a column which has a sum function in yii2

百般思念 提交于 2019-12-12 04:07:14

问题


I have two tables - parties, bills. In parties table the fiels are parties_partyname,parties_district. And in the bills table it has field bills_partyname, billamount,billdate. I want to see the query as

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

My Search Model looks like -

$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');

Parties index.php

'parties_partyname',
        'parties_district',

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

I've added public $sale in the parties model


回答1:


If you want use the activeQuery like you shown you should use

$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');

otherwise you can use a simple (activeRecord) findBySql() (this give you the query for 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);

if you use instead

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

you get all the models

for grid view if you value is the same of the attribute value use

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

without value =>



来源:https://stackoverflow.com/questions/37028572/getting-not-set-when-joining-a-column-which-has-a-sum-function-in-yii2

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!