问题
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