How to make yii2 query using where() - andWhere()? - yii2

I have make one query using conditional statement.
$query = Student::find()
->where('status=1');
if(isset($params['standard_id']) AND !empty($params['standard_id'])){
$query->andWhere(["standard_id"=>$params['standard_id']]);
}
if(isset($params['section_id']) AND !empty($params['section_id'])){
$query->andWhere(["section_id"=>$params['section_id']]);
}
if(isset($params['year']) AND !empty($params['year'])){
$query->andWhere(["year"=>$params['year']]);
}
//$result = $query->all();
return $query;
Mysql
select *from student where satus=1 and standard_id=3 and section_id=1 and year=2015
If possible to make using where - andWhere in yii2?
please help me

Try this.can't understand your question clearly. may be this will help you.
$model = User::find()
->where('satus> :satus', [':satus' => '1'])
->andWhere('standard_id= :standard_id', [':standard_id' => 3])
->andWhere('section_id= :section_id', [':section_id' => 1])
->andWhere('year= :year', [':year' => 2015])
->all();

Yes, you can use both where() and andWhere(). This should helps you to understand how it works.
https://github.com/yiisoft/yii2/blob/master/framework/db/QueryTrait.php#L101

Related

Yii2 insert query with bindparam for sql injection

I want use but not work please help me.
$sql = Yii::$app->db("INSERT INTO posts(name) VALUES(:name)");
$sql->bindValues([':name' => 'John']);
$sql->execute();
try create command exceute
Yii::$app->db->createCommand('INSERT INTO posts(name) VALUES(:name)')
->bindValues([':name' => 'John'])->execute();

How to make multiple UPSERT in Yii2?

I am using Yii2 advance template. I have to insert 1000 to 2000 records in MySql Database.
Is it possible to make Multiple UPSERT Query in Yii2.
Please help me with your suggestion/answers. Thank you.
Since version 2.0.14 you have upsert() available.
Your code could look something like this:
$insertValues = [
'timestamp' => gmdate('YmdH'),
'entry_id' => $this->id,
'view_count' => 1,
];
$updateValues = ['view_count' => new \yii\db\Expression('table_name.view_count + 1')];
Yii::$app->db->createCommand()->upsert('table_name', $insertValues, $updateValues)->execute();
You can find the full documentation here: https://www.yiiframework.com/doc/api/2.0/yii-db-command#upsert()-detail
Try with modified batchInsert() method:
$db = \Yii::$app->db;
$sql = $db->queryBuilder->batchInsert($table, $fields, $rows);
$db->createCommand($sql . ' ON DUPLICATE KEY UPDATE')->execute();

How to use not equal to inside a Yii2 query

I want to use a yii2 query in which I want to check a not equal to condition.
I tried like this but it didn't give the desired results. How do I do it?
$details = MovieShows::find()
->where(['movie_id'=>$id])
->andWhere(['location_id'=>$loc_id])
->andWhere(['cancel_date'=>!$date])
->all();
In this case you need to use operator format: [operator, operand1, operand2, ...]. So your code should look like this:
$details = MovieShows::find()
->where(['movie_id'=>$id])
->andWhere(['location_id'=>$loc_id])
->andWhere(['<>','cancel_date', $date])
->all();
More about using where method and operator format
You can also try this:
$details = MovieShows::find()->where(['movie_id'=>$id])
->andWhere(['!=', 'cancel_date', $date])->all();
for Greater than
$details = MovieShows::find()->where(['movie_id'=>$id])
->andWhere(['>', 'cancel_date', $date])->all();
for less than
$details = MovieShows::find()->where(['movie_id'=>$id])
->andWhere(['<', 'cancel_date', $date])->all();
More check here
Maybe this one help...:)
$query->andFilterWhere([ 'or',
['<=', 'affidavit_cont', 0],
['=', 'affidavit_cont1', 0],
['>', 'affidavit_cont2', 0],
['!=', 'affidavit_cont3', $this->affidavit3],
['in', 'attempt_count', $this->attempted],
]);
$query->andFilterWhere(['like', 'job_invoice.paid_status', '',]);
$query->andFilterWhere(['in', 'status_id', $this->status_id]);
$query->andFilterWhere(['between', 'last_attempt',
strtotime(Utility::convertDate2Db($this->from_date)),
strtotime(Utility::convertDate2Db($this->to_date))
]);
The better and safe way to apply a condition.
Booking::find()->where('tour_id = :tour_id and id != :id', ['tour_id'=> $chk->tour_id, 'id' => $id])->all();
You can use this
$this->find()->where(['resource_id' => $resource_id]) ->andWhere(['>=', 'start_time', $start_time])->all();
In addiction to the #tony answer, for those who need to encapsulate a subquery here there's a quick example:
$users = User::find()
->where([
'not in',
'id',
(new Query())
->select('user_id')
->from(MyTable::tableName())
->where(['related_id'=>$myRelatedId])
->all();
<?= $form->field($model, 'first_name')->dropDownList(
ArrayHelper::map(user::find()->where([
'not in ' ,
'first_name',
patient::find()
->select([ 'patient_name' ])
->asArray()
])
->all(),'id','first_name')
Maybe it help you for whom need to use subquery .
In case anyone reading this needs to use a REGEXP or similar, this works in Yii2 (2.0.15.1):
->andWhere(['NOT REGEXP', 'column','[A-Za-z]'])
You can just use the below pasted code:
$details = MovieShows::find()->where(['movie_id'=>$id])
->andWhere(['location_id'=>$loc_id])
->andWhere(['not in','cancel_date',$date])->all();

Laravel 4.x, Eloquent multiple conditions

I've tried to this:
Product::where(['product_id' => $product->id, 'catalog_id' => $key])->first();
This isn't working at all. When I'm doing this:
Product:where('product_id', $product->id)->where('catalog_id', $key)->first();
It just works fine. I've searched in the documentation of Laravel,
and found nothing.
Is there any option to using the where function with an array in it ?
You need to use where() individually. If you want to dynamically building the query you can do something like:
$wheres = array('product_id' => $product->id, 'catalog_id' => $key);
$q = new Product;
foreach ( $wheres as $k => $v ) {
$q = $q->where($k, $v);
}
$products = $q->first();
In fact we were all wrong ;)
As of latest version of the framework you can do exactly what you wanted.
Check this commit and update Laravel if you need that feature.
https://github.com/laravel/framework/commit/87b267a232983abdac7c23c2dc6b1b270dd24b8a
Product::whereNested(function($query) use ($key, $product){
$query->where('product_id', $product->id);
$query->where('catalog_id', $key);
})->get();
Laravel's wheres use an and condition by default:
$products = Product::where('this','=','that')->where('something','=','hello')->get();
is somewhat equivalent to:
SELECT * FROM products WHERE this = 'that' AND something = 'hello';
You simply chain the ->where() methods together. No need for an array.
If you want to use an or condition:
$products = Product::where('this','=','that')->orWhere('something','=','hello')->get();

CakePHP: How can I use a "HAVING" operation when building queries with find method?

I'm trying to use the "HAVING" clause in a SQL query using the CakePHP paginate() method.
After some searching around it looks like this can't be achieved through Cake's paginate()/find() methods.
The code I have looks something like this:
$this->paginate = array(
'fields' => $fields,
'conditions' => $conditions,
'recursive' => 1,
'limit' => 10,
'order' => $order,
'group' => 'Venue.id');
One of the $fields is an alias "distance". I want to add a query for when distance < 25 (e.g. HAVING distance < 25).
I have seen two workarounds so far, unfortunately neither suit my needs. The two I've seen are:
1) Adding the HAVING clause in the "group" option. e.g. 'group' => 'Venue.id HAVING distance < 25'. This doesn't seem to work when used in conjunction with pagination as it messes up the initial count query that is performed. (ie tries to SELECT distinct(Venue.id HAVING distance < 25) which is obviously invalid syntax.
2) Adding the HAVING clause after the WHERE condition (e.g. WHERE 1 = 1 HAVING field > 25) This doesn't work as it seems the HAVING clause must come after the group statement which Cake is placing after the WHERE condition in the query it generates.
Does anyone know of a way to do this with CakePHP's find() method? I don't want to use query() as that would involve a lot of rework and also mean I'd need to implement my own pagination logic!
Thanks in advance
You have to put it with the group conditions. like this
$this->find('all', array(
'conditions' => array(
'Post.length >=' => 100
),
'fields' => array(
'Author.id', 'COUNT(*) as Total'
),
'group' => array(
'Total HAVING Total > 10'
)
));
Hope it helps you
I used the following trick to add my own HAVING clause at the end of my WHERE clause. The "dbo->expression()" method is mentioned in the cake sub-query documentation.
function addHaving(array $existingConditions, $havingClause) {
$model = 'User';
$db = $this->$model->getDataSource();
// Two fun things at play here,
// 1 - mysql doesn't allow you to use aliases in WHERE clause
// 2 - Cake doesn't allow a HAVING clause separate from a GROUP BY
// This expression should go last in the WHERE clause (following the last AND)
$taut = count($existingConditions) > 0 ? '1 = 1' : '';
$having = $db->expression("$taut HAVING $havingClause");
$existingConditions[] = $having;
return $existingConditions;
}
As per the manual, CakePHP/2 supports having at last. It was added as find array parameter on version 2.10.0, released on 22nd July 2017.
From the 2.10 Migration Guide:
Model::find() now supports having and lock options that enable you to
add HAVING and FOR UPDATE locking clauses to your find operations.
Just had the same problem. I know, one is not supposed to modify the internal code but if you open the PaginatorComponent and you modify line 188:
$count = $object->find('count', array_merge($parameters, $extra));
to this:
$count = $object->find(
'count',
array_merge(array("fields" => $fields),$parameters, $extra)
);
Everything will be fixed. You will be able to add your HAVING clause to the 'group' and the COUNT(*) won't be a problem.
Or, make line:
$count = $object->paginateCount($conditions, $recursive, $extra);
to include the $fields:
$count = $object->paginateCount($fields,$conditions, $recursive, $extra);
After that, you can "override" the method on the Model and make sure to include the $fields in the find() and that's it!, =P
Here is another idea that doesn't solve the pagination issue, but it is clean since it just overrides the find command in AppModel. Just add a group and having element to your query and this will convert to a HAVING clause.
public function find($type = 'first', $query = array()) {
if (!empty($query['having']) && is_array($query['having']) && !empty($query['group'])) {
if ($type == 'all') {
if (!is_array($query['group'])) {
$query['group'] = array($query['group']);
}
$ds = $this->getDataSource();
$having = $ds->conditions($query['having'], true, false);
$query['group'][count($query['group']) - 1] .= " HAVING $having";
CakeLog::write('debug', 'Model->find: out query=' . print_r($query, true));
} else {
unset($query['having']);
}
}
return parent::find($type, $query);
}
Found it here
https://groups.google.com/forum/?fromgroups=#!topic/tickets-cakephp/EYFxihwb55I
Using 'having' in find did not work for me. Instead I put into one string with the group
" group => product_id, color_id having sum(quantity) > 2000 " and works like a charm.
Using CakePHP 2.9