There is a table "Apartments". Here is a need to create a query in Yii. How to do it?
SQL query:
SELECT *
FROM {{apartments}}
WHERE agent_id = 4
UNION
SELECT *
FROM {{apartments}}
WHERE agent_id != 4
In my cintroller
$arrSql[] = 'SELECT * FROM {{apartments}} WHERE agent_id=:agent_id';
$arrSql[] = 'SELECT * FROM {{apartments}} WHERE agent_id!=:agent_id';
$data = Apartments::model()->findAllBySql(implode(' UNION ', $arrSql), array(
':agent_id' => Yii::app()->user->id,
':status' => Apartments::STATUS_REMOVED
));
$dataProvider = new CArrayDataProvider($data);
But not work pagination and filter in my widget CGridList.
As i know, you can use the CDbCommand like this:
$apartments2 = Yii::app()->db->createCommand()
->select("*")
->from('apartments')
->where('agent_id!=:agent_id', array(':agent_id'=>4))
->getText();
$apartments = Yii::app()->db->createCommand()
->select("*")
->from('apartments')
->where('agent_id=:agent_id', array(':agent_id'=>4))
->union($apartments2)
->queryRow();
you can find your result in the $apartments as an array.
EDIT:
if you want to use a CActiveDataProvider, you need to use CSqlDataProvider:
$sql='SELECT *
FROM {{apartments}}
WHERE agent_id = 4
UNION
SELECT *
FROM {{apartments}}
WHERE agent_id != 4';
$dataProvider=new CSqlDataProvider($sql, array(
'totalItemCount'=>$count,
'sort'=>array(
'attributes'=>array(
'agent_id', //and all other atributes with withc you want to sort
),
),
'pagination'=>array(
'pageSize'=>10,
),
));
Its very simple
(SELECT *
FROM {{apartments}}
WHERE `agent_id` = '4')
UNION ALL
(SELECT *
FROM {{apartments}}
WHERE `agent_id` <> '4')
Let me know if that worked for you..
Related
How can I convert this raw query into query builder yii2 as I am getting the record using sub-query:
RAW QUERY:
SELECT *
FROM (
SELECT DISTINCT `comp`.*,TIMESTAMPDIFF(HOUR,comp.created_date,comp.updated_date)
AS hours
FROM `complaints` `comp`
INNER JOIN `complaint_log` `comp_log` ON comp_log.`comp_id` = comp.`id`
WHERE ((comp.name LIKE '%%' OR comp.id LIKE '%%' OR comp.phone_no LIKE '%%')
AND DATE(comp.created_date)
BETWEEN '2018-01-01' AND '2020-03-20')
AND (comp.is_delete = 0)
ORDER BY `comp`.`id` DESC, `comp`.`created_date` DESC)
AS cte_name WHERE hours > 120;
Yii2 Query
$query = (new \yii\db\Query())
->select('comp.*')
->from('complaints comp
->distinct()
->innerJoin('complaint_log as comp_log', 'comp_log.`comp_id` =comp.`id`')
->where($search)
->andWhere('comp.is_delete = 0')
->orderBy("comp.id DESC")
->addOrderBy('comp.created_date DESC');
Try following code:
$subquery = (new \yii\db\Query())
->select(['comp.*', 'TIMESTAMPDIFF(HOUR, comp.created_date, comp.updated_date) AS hours'])
->distinct()
->from('complaints comp')
->innerJoin('complaint_log comp_log', 'comp_log.comp_id = comp.id')
->where(['or',
['like', 'comp.name', $search_name],
['or',
['like', 'comp.id', $search_id],
['like', 'comp.phone_no', $search_phone],
]
])
->andWhere('DATE(comp.created_date) BETWEEN :cStart AND :cEnd', [':cStart' => '2018-01-01', ':cEnd' => '2020-03-20'])
->andWhere(['comp.is_delete' => 0])
->orderBy(['comp.id' => SORT_DESC, 'comp.created_date' => SORT_DESC])
;
$query = (new \yii\db\Query())
->select('cte_name.*')
->from(['cte_name' => $subquery])
->where(['>', 'cte_name.hours', 120])
;
You can use createCommand() function: use below query.
$connection = \Yii::$app->db;
$query = $connection->createCommand(
'
SELECT * FROM (
SELECT DISTINCT comp.*,TIMESTAMPDIFF(HOUR,comp.created_date,comp.updated_date) AS hours
FROM complaints comp
INNER JOIN complaint_log comp_log ON comp_log.comp_id = comp.id
WHERE ('.$search.')
AND (comp.is_delete = 0)
ORDER BY comp.id DESC, comp.created_date DESC
) AS cte_name WHERE hours > 120;
');
$data = $query->queryAll();
Put your raw query in createCommand() function. Here i used $search variable as you used in your sub query
I understand that to do a select query is
$bearLawly = Bear::where('name', '=', 'Lawly')->first();
but how to I do a select query such as
SELECT * FROM bear where name = 'abc' AND age => '5' AND title = 'kid' ORDER BY name LIMIT 5, 10
Thanks!
You may try this:
$bearLawly = Bear::where('name', 'abc') // By default = will be used, so optional
->where('age', '>=', '5')
->where('title', 'kid')
->orderBy('name') // or orderBy('name', 'desc') for reverse
->take(5)->skip(10)->get();
According to following query:
SELECT * FROM bear where name = 'abc' AND age => '5' AND title = 'kid' ORDER BY name LIMIT 5, 10
Just chain them:
$bearLawly = Bear::where('name', 'Lawly')->where('age', '5')->first();
How would i convert below query to sub query?
I don't want to use JOINS I want to do same through sub query. i-e I need three subqueries out of the three joins. How it would be possible for below query ?
protected $_name = 'sale_package_features';
public function getAllSalePackageFeatures(){
$sql = $this->select()->setIntegrityCheck(false)
->from(array('spf' => $this->_name))
->joinLeft(array('sd' => 'sale_devices'),'sd.sale_device_id = spf.sale_device_id',array('sd.sale_device_name AS deviceName'))
->joinLeft(array('sp' => 'sale_packages'),'sp.sale_package_id = spf.sale_package_id',array('sp.sale_package_name AS packageName'))
->joinLeft(array('sf' => 'sale_features'),'sf.sale_feature_id = spf.sale_feature_id',array('sf.sale_feature_name AS featureName'))
->where('sf.parent_id != ?',0)
->order('spf.sale_package_feature_id ASC');
return $sql->query()->fetchAll();
}
Edited :
SELECT
`spf`.*, `sd`.`sale_device_name` AS `deviceName`,
`sp`.`sale_package_name` AS `packageName`,
`sf`.`sale_feature_name` AS `featureName`
FROM `sale_package_features` AS `spf`
LEFT JOIN `sale_devices` AS `sd`
ON sd.sale_device_id = spf.sale_device_id
LEFT JOIN `sale_packages` AS `sp`
ON sp.sale_package_id = spf.sale_package_id
LEFT JOIN `sale_features` AS `sf`
ON sf.sale_feature_id = spf.sale_feature_id
WHERE (sf.parent_id != 0)
ORDER BY `spf`.`sale_package_feature_id` ASC
You can use
$dbAdapter = Zend_Db_Table::getDefaultAdapter();
$subSelect = $dbAdapter
->select()
->from( 'tablename',
array(
'col1_alias' => 'column1_name',
'col2_alias' => 'column2_name',
))
->where('somefield = ?', $value_to_be_quoted);
$select = $dbAdapter
->select()
->from(array('sub_alias' => $subSelect ))
->where('otherfield = ?', $other_value_to_be_quoted);
$sql = $select->assemble();
$sql will contain
SELECT
sub_alias . *
FROM
(SELECT
tablename.column1_name AS col1_alias,
tablename.column2_name AS col2_alias
FROM
tablename
WHERE
(somefield = 'quoted_value')) AS sub_alias
WHERE
(otherfield = 'quoted_other_value')
If you need to use SELECT .. WHERE x IN (subselect) than go with
$select->where( 'column IN (?)', new Zend_Db_Expr($subselect->assemble()) );
I am not able to convert the below query into Zend_Db_Table_Select query.
SELECT GROUP_CONCAT(wallet_transaction_id) as wallet_transaction_ids,transaction_type,source,status
FROM(
SELECT wallet_transaction_id, transaction_type, source, status
FROM ubiw_transactions_wallet
WHERE (game_id = '1292') AND (player_id = 1538)
ORDER BY date DESC LIMIT 100
) a
GROUP BY a.transaction_type,a.status, a.transaction_type;
any help is appreciated.
thanks,
shiv
// Maybe need some changes
$table = new Zend_Db_Table('ubiw_transactions_wallet');
$subSelect = $table->select()
->from('ubiw_transactions_wallet', array('wallet_transaction_id', 'transaction_type', 'source', 'status'))
->where($table->getAdapter()->quoteInto('game_id = ?', 1292))
->where($table->getAdapter()->quoteInto('player_id = ?', 1538))
->order('`date` DESC')
->limit(100);
$mainSelect = $table->select()
->setIntegrityCheck(false)
->from(array('a' => $subSelect), array('wallet_transaction_ids' => new Zend_Db_Expr('GROUP_CONCAT(wallet_transaction_id)'), 'transaction_type', 'source', 'status'))
->group(array('a.transaction_type', 'a.status', 'a.transaction_type'));
$result = $table->fetchAll($select);
I have a query as below:
select status, count(id) as units from myTable group by status
I have a Zend_Db_Table object at my displosal for the table in use, i am trying the below mentioned snippet to create the query above:
$objTable= new Application_Model_DbTable_MyTable();
$select = $objTable -> select(Zend_Db_Table::SELECT_WITH_FROM_PART)
-> setIntegrityCheck(false); // i am also using joins to create the query, but this is not of concern
$select -> columns(array(
'status' => new Zend_Db_Expr('DISTINCT(STATUS)'),
'units' => new Zend_Db_Expr('COUNT(id)')
));
$select -> group('status');
the query created from the above snippet is as follows:
select myTable.*, DISTINCT(STATUS) as status, COUNT(id) as units from myTable group by status
I want to remove the myTable.* from the query generated.
$select = $db ->select()
->distinct()
->from('myTable',array('status', 'COUNT(id) as units'))
->group('status');
Try this instead.
$select = new Zend_Db_Select;
$select->from(
# table
array(
't' => 'myTable'
),
# columns
array(
'status' => 'DISTINCT(STATUS)',
'units' => 'COUNT(id)',
));
->group('status');
The problem is Zend_Db_Select will automatically added table.* to your query if there's no column specified in ->from( clause