yii2 select NULL value in query (select NULL as column, ...) - php

Is there a way to select NULL value or an exact string in a query in YII2?
I am trying to join 3 queries and I need the same number of columns queries and something like "select NULL as returned, submitted, amount, NULL as iamount....."
Example:
$subQuery2 = Loan::find()->select('person_id')->where(['sheet_id' => $id]);
$query2 = new Query();$query2 = new Query();
$query2->select(['last_name','first_name','fc.tax','NULL as returned','fc.submitted','fc.amount','NULL as iamount','NULL as interest',
'b.month','b.year','b.nb'])
->from('sheet as b')
->join('JOIN', 'fee as fc',
'b.id = fc.sheet_id')
->join('JOIN','person','fc.person_id = person.id')
->where(['b.id' => $id])
->andWhere(['not in', 'person_id', $subQuery2]);
$query = new Query();
$query->
select(['last_name','first_name','fc.tax','fi.returned','fc.submitted','fc.amount','fi.amount as iamount','fi.interest',
'b.month','b.year','b.nb'])
->from('sheet as b')
->join('RIGHT JOIN', 'fee as fc',
'b.id = fc.sheet_id')
->join('JOIN','person','fc.person_id = person.id')
->join('LEFT JOIN','loan as fi',
'b.id = fi.sheet_id and fc.person_id = fi.person_id')
->where(['b.id' => $id])
->union($query2)
->orderBy(['last_name' => SORT_DESC]);

Yes, you have two ways to do it:
$query = new Query();
$query->select([
new Expression('NULL as test')
'test2' => new Expression('NULL'),
])->from('sheet as b');
Both of selects will do the same, but the second line (test2) is preferable as it is more DBMS-agnostic.

Related

How can I count in yii2?

I want to count for each of the values in the select. I need to know how many values there are in each a.merk, b.brandstof, a.bouwjaar, k.kleur, t.transmissie. So I need 5 different values. How can I do this?
public function searchFilter() {
$query = (new Query())
->select([
'GROUP_CONCAT(DISTINCT(a.merk), ".", m.merk ORDER BY a.merk ASC) merk',
'GROUP_CONCAT(DISTINCT(b.brandstof) ORDER BY b.brandstof ASC) brandstof',
'GROUP_CONCAT(DISTINCT(a.bouwjaar) ORDER BY a.bouwjaar DESC) bouwjaar',
'GROUP_CONCAT(DISTINCT(k.kleur) ORDER BY k.kleur ASC) kleur',
'GROUP_CONCAT(DISTINCT(t.transmissie) ORDER BY t.transmissie ASC) transmissie',
])
->from('auto_new a')
->join('INNER JOIN', 'tbl_merken m', 'a.merk = m.merk_id') //Merk
->join('INNER JOIN', 'tbl_kleur k', 'a.kleur = k.kleur_id') //Kleur
->join('INNER JOIN', 'tbl_transmissie t', 'a.transmissie = t.transmissie_id') //Transmissie
->join('INNER JOIN', 'tbl_brandstof b', 'a.brandstof = b.brandstof_id'); //Brandstof
return $query;
}
this is the output I get.
In this function I execute the query.
public function actionSearchfilter($ac) {
Yii::$app->response->format = Response::FORMAT_JSON;
$query = Car::searchFilter()->where(['a.ac' => $ac, 'a.flag' => '1'])->all();
return $query;
}
I only need to count the DISTINCT values.

Convert from query to ModelSearch of Yii2

I'm new in Yii2, and I have a query with right result:
SELECT DISTINCT workloadTeam.project_id, wp.project_name, workloadTeam.user_id, workloadTeam.commit_time, wp.workload_type FROM
(SELECT p.id, p.project_name, w.user_id, w.commit_time, w.comment, w.workload_type
FROM workload as w, project as p
WHERE w.user_id = 23 AND p.id = w.project_id) wp
INNER JOIN workload as workloadTeam ON wp.id = workloadTeam.project_id
But in my ModelSearch.php, I wrote:
$user_id = Yii::$app->user->id;
$subquery = Workload::find()->select('p.id', 'p.project_name', 'w.user_id', 'w.commit_time', 'w.comment', 'w.workload_type')
->from(['project as p', 'workload as w'])
->where(['user_id' => $user_id, 'p.id' => 'w.project_id']);
$query = Workload::find()
->select(['workloadTeam.project_id', 'wp.project_name', 'workloadTeam.user_id', 'workloadTeam.from_date', 'workloadTeam.to_date', 'workloadTeam.workload_type', 'workloadTeam.comment'])
->where(['', '', $subquery]);
$query->join('INNER JOIN', 'workload as workloadTeam', 'wp.id = workloadTeam.project_id');
It happended error:
SELECT COUNT(*) FROM `workload` INNER JOIN `workload` `workloadTeam` ON wp.id = workloadTeam.project_id WHERE `` (SELECT p.project_name `p`.`id` FROM `project` `p`, `workload` `w` WHERE (`user_id`=20) AND (`p`.`id`='w.project_id'))
And I can't fix it with right query above.
You have any solution about this?
Is this error shown in the Yii-debug toolbar? Then your query (which you mentioned as error) is probably only the count from the query which is listed before.
You missed to add the sub-query in from clause like you shown in your working sql. Add this in your where clause were just the wrong place. Put sub-queries in whereconditions, if you have scalar results, because you have to use this result with operands like =, >=, in...
This could work:
$user_id = Yii::$app->user->id;
$subquery = Workload::find()->select([
'p.id as id',
'p.project_name as project_name',
'w.user_id as user_id',
'w.commit_time as commit_time',
'w.comment as comment',
'w.workload_type as workload_type'
])
->from([
'project as p',
'workload as w'
])
->where([
'user_id' => $user_id,
'p.id' => 'w.project_id'
]);
$query = Workload::find()
->select([
'workloadTeam.project_id',
'wp.project_name',
'workloadTeam.user_id',
'workloadTeam.from_date',
'workloadTeam.to_date',
'workloadTeam.workload_type',
'workloadTeam.comment'
])
->from([$subquery => 'wp']); //you were missing this line
$query->join('INNER JOIN', 'workload as workloadTeam', 'wp.id = workloadTeam.project_id');
But you don't use any selects from your workload table in your main-query $query...
Since I don't know what's your goal to achieve I can't help you at this topic...

Use limit range in yii2?

I want to get data from db using limit 12,20 .
Here is my code:
$Query = new Query;
$Query->select(['um.id as USERid', 'um.first_name', 'um.last_name', 'um.email', 'COUNT(g.id) as guestCount'])
->from('user_master um')
->join('LEFT JOIN', 'guest g', 'g.user_id = um.id')
->limit(12,20)
->groupBy('um.id')
->orderBy(['um.id' => SORT_DESC]);
$command = $Query->createCommand();
$evevtsUserDetail = $command->queryAll();
It is not working. It is giving me all rows. I also tried ->limit([12,20]), not working.
But when I am using limit(12) then I am getting 12 rows.
I want to get rows in limit 12,20 . What should I have to do for that in my this code?
Try this:
$Query = new Query;
$Query->select(['um.id as USERid', 'um.first_name', 'um.last_name','um.email','COUNT(g.id) as guestCount'])
->from('user_master um')
->join('LEFT JOIN', 'guest g', 'g.user_id = um.id')
->limit(20)
->offset(12)
->groupBy('um.id')
->orderBy(['um.id' => SORT_DESC]);
Offset() specifies the starting point and limit() specifies the Number of records. If you want records between 12 and 20 then use limit(8).
For More Info:
http://www.bsourcecode.com/yiiframework2/select-query-model/#offset
http://www.yiiframework.com/doc-2.0/yii-db-querytrait.html#offset%28%29-detail
you can do with Active record
$model = YourModel::find()->where('user_id = :user_id', [':user_id' => \Yii::$app->user->id])->limit(12,20)->all();
OR
$model = YourModel::find()->where('user_id = :user_id', [':user_id' => \Yii::$app->user->id])->with(['job','job.jobRecipient'])->limit(12)->all();

How can I turn ZF ->joinLeft()s into a Subquery?

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()) );

writing a subquery using Zend_Db_Table_Select

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

Categories