I have two table dataset_type and type, now in the type model, I want to create CActiveDataProvider and use CDbCriteria in sql is
select type.name, type.description , count(dataset_type.dataset_id) as number
from type ,dataset_type
where type.id=dataset_type.type_id
group by type.id
How can i write by CDbCriteria
I try to write
$criteria=new CDbCriteria;
$criteria->select='type.name, type.description, count(dataset_type.dataset_id) as number';
$criteria->join='LEFT JOIN dataset_type ON dataset_type.type_id=id';
$criteria->group='type.id';
//$criteria->compare('id',$this->id);
//$criteria->compare('LOWER(name)',strtolower($this->name) , true);
//$criteria->compare('LOWER(description)',strtolower($this->description) , true);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
but it shows error
CDbCommand failed to execute the SQL statement: SQLSTATE[42702]: Ambiguous column: 7 ERROR: column reference "id" is ambiguous at character 163. The SQL statement executed was:
SELECT COUNT(*)
FROM (SELECT type.name, type.description, count(dataset_type.dataset_id) as number
FROM "type" "t"
LEFT JOIN dataset_type ON dataset_type.type_id=id
GROUP BY type.id) sq
You should use t.id in following line :-
$criteria->join='LEFT JOIN dataset_type ON dataset_type.type_id=t.id';
As t is alias of type table.
dataset_type.type_id=id
should be
dataset_type.type_id=type.id
$criteria->join='LEFT JOIN dataset_type ON dataset_type.type_id=type.id';
If I were U I wrote it without criteria via createCommand I had the problem with my PostgreSQL database when I use JOIN and GROUP BY together. Look at this code:
$result = Yii::app()->db->createCommand()
->select("t.shop_id, s.name as name, s.schema as schema, sum(t.sales) as sales, sum(t.price) as price, sum(t.net_price) as net_price")
->from("pos_sales t")
->join("shops s", "t.shop_id=s.id")
->where("t.sales_year=:year AND t.sales_month=:month", array(':year' => $this->year, ':month' => $this->month))
->group("t.shop_id, s.name, s.schema")
->queryAll();
The tables are here
create table shops(
id serial primary key,
name varchar(255),
schema varchar(255),
store_id smallint,
pos_sales_date date,
active boolean
);
create table pos_sales(
shop_id integer NOT NULL,
sales_date date NOT NULL,
sales_year smallint,
sales_month smallint,
sales integer,
price numeric(12,2),
net_price numeric(12,2)
);
alter table pos_sales add constraint pos_sales_pkey PRIMARY KEY(shop_id, sales_date);
alter table pos_sales add constraint fk_PosSales_Shops FOREIGN KEY (shop_id) REFERENCES shops(id);