Yii2 query with where and or - yii2

I'm struggling with this one, I've tried allsorts of combinations and nothing comes up with what I want.
So my sql code is
select * from table where organisation_id`= org_id
AND due_at` <= start_date
AND due_at` >= end_date
AND category_id = cat_id
and ((standard_task_template_id is null) or (standard_task_template_id not in (standardQuery))
and my yii2 code is
$query = TaskEventAllocation::find()
->where([TaskEventAllocation::tableName().'.organisation_id'=> $organisation_id])
->andWhere(['<=','due_at', $unix_end_date->getTimestamp()])
->andWhere(['>=', 'due_at', $unix_start_date->getTimestamp()])
$query->andWhere(['tc.id' => $cat_or_group_id]);
then if I add
$query->andWhere('and',['is', 'standard_task_template_id', new \yii\db\Expression('null')],['or', ['not in', 'standard_task_template_id', $standardTaskIds]]);
it returns
SELECT `t_task_event_allocation`.*
FROM `t_task_event_allocation`
WHERE (`t_task_event_allocation`.`organisation_id`=:qp3)
AND (`due_at` <= :qp4)
AND (`due_at` >= :qp5)
AND (`group_id` != :qp6) A
ND (`tc`.`id`=:qp7)
AND (and)
I've tried
$query->andWhere('or',['is', 'standard_task_template_id', new \yii\db\Expression('null')],['and', ['not in', 'standard_task_template_id', $standardTaskIds]]);
that produces the same as above but with in an or in brackets
$query->andWhere(['is', 'standard_task_template_id', new \yii\db\Expression('null')], 'or', ['not in', 'standard_task_template_id', $standardTaskIds]);
produces an error saying argument 2 must be of the type array

->andWhere([
'or',
['standard_task_template_id' => null],
['not in', 'standard_task_template_id', $standardTaskIds]
]);

Related

Yii2 update query with where in and not in condition

How can I write update query with where, in and not in condition.
I tried this one but it's not working properly. It updates all rows in a table. Not only working for mentioned rows but also all rows.
$postval=('2,4,5,7');
$netchk=TblNetwork::updateAll(['status' => 0],['AND',
'status = 1', ['NOT IN', 'network_id_pk', $postval]
]);
You should use array of IDs for NOT IN condition (in you're example you're using string with list of IDs):
$postval = [2, 4, 5, 7];
$netchk = TblNetwork::updateAll(['status' => 0], [
'AND',
'status = 1',
['NOT IN', 'network_id_pk', $postval]
]);

Laravel Eloquent orWhere issues

Been wandering what's wrong with my query should be as easy as it seems.
its more like i'm creating a select * from table where (a = 1 and b =2)
or (a = 2 and b = 1) type of query. Here's my eloquent.
return $query->where(function($q) use ($brand, $influencer, $agency){
$q->where([
'sender_id' => $brand,
'receiver_id' => $influencer
]);
$q->orWhere([
'sender_id' => $influencer,
'receiver_id' => $brand
]);
});
I have this query in my eloquent but when display in debug bar it's showing
select count(*) as aggregate
from `chat_messages`
where ((`sender_id` = '415' and `receiver_id` = '1159')
or (`sender_id` = '1159' or `receiver_id` = '415'))
and i wanted it to be "AND" inside the second parenthesis group
select count(*) as aggregate
from `chat_messages`
where ((`sender_id` = '415' and `receiver_id` = '1159')
or (`sender_id` = '1159' AND `receiver_id` = '415'))
If you call orWhere() with an array, it uses OR in front and between the individual constraints.
Use this:
return $query->where(function($q) use ($brand, $influencer, $agency){
$q->where([
'sender_id' => $brand,
'receiver_id' => $influencer
])->orWhere(function($q) use ($brand, $influencer) {
$q->where([
'sender_id' => $influencer,
'receiver_id' => $brand
]);
});
});

Yii2 where() variable condition

I want when currency = 'sum' sort by and Where(['between', 'price', $min_price, $max_price]) and when currency = 'y.e.' sort by andWhere(['between', 'price', $min_price*2, $max_price*2]). How to write the sql query in yii2?
$anmt_t = (new \yii\db\Query())
->select(['*'])
->from('anmt')
->where(['status' => 'confirmed'])
->andWhere(['between', 'price', $min_price, $max_price, when (currency = 'sum')])
->andWhere(['between', 'price', $min_price*2, $max_price*2, when (currency = 'y.e.')])
->all();
Try using CASE :
$anmt_t = (new \yii\db\Query())
->select(['*'])
->from('anmt')
->where(['status' => 'confirmed'])
->andWhere('
CASE
WHEN currency = "sum" THEN price BETWEEN :mp1 AND :mx1
WHEN currency = "y.e." THEN price BETWEEN :mp2 AND :mx2
END
')
->params([
'mp1' => $min_price,
'mx1' => $max_price,
'mp2' => $min_price * 2,
'mx2' => $max_price * 2,
])
->all();
Not tested
I'd personally favor using Yii2, rather than writing a long query
$condition = currency == 'y.e.' ? ['between', 'price', $min_price *2, $max_price*2] : ['between', 'price', $min_price, $max_price];
then
$anmt_t = (new \yii\db\Query())
->select(['*'])
->from('anmt')
->where(['status' => 'confirmed'])
->andWhere($condition)
->all();

Not equal condition with findAll()

I am trying to pull record from a table using the following code
$userId = Yii::$app->user->id;
$lists = PromoLists::findAll(['user_id' => $userId, 'list_type' => 'custom']);
which outputs a query like below
select * from promo_lists where user_id ='$userId' and list_type='custom'
But i am unable to find any thing in the documentation that would help me achieve it with the following condition.
select * from promo_lists where user_id ='$userId' and list_type='custom' and status!='deleted'
as the status is an ENUM field and there are 4 different status
'active','pending','rejected','deleted'
currently i used the following approach
PromoLists::findAll(['user_id' => $userId, 'list_type' => 'custom', 'status'=>['active','pending','rejected']]);
which outputsthe following query
select * from promo_lists where user_id ='$userId' and list_type='custom' and status in ('active','pending','rejected')
which somehow achieves the same thing but this query would need to be edited every time when there is a new status type added to the table column status.
i know i can do this by using PromoLists::find()->where()->andWhere()->all()
but how to check with != / <> operator using findAll().
Simply like this:
PromoLists::find()->where(['and',
[
'user_id' => $userId,
'list_type' => 'custom',
],
['<>', 'status', 'deleted'],
])->all();
Using operator format in condition
http://www.yiiframework.com/doc-2.0/guide-db-query-builder.html#operator-format
PromoLists::find()
->andWhere([
'user_id' => $userId,
'list_type' => 'custom',
['!=', 'status', 'deleted']
])
->all();

Laravel - where >= not working

I'm trying to get a database entry with this lines of code:
$hoy = date('YYYY-MM-DD');
$stay = Stay::where('guest', '=', $id )
->where('indate', '<=', $hoy )
->where('outdate', '>=', $hoy )
->get( array( 'id', 'room', 'bed', 'guest', 'booking', 'indate', 'outdate' ) );
The thing is, if I remove the outdate >= $hoy line, it works. But with it, it doesn't.
The line i'm trying to retrieve has it's outdate set to 2015-12-02, so it should return it.
Any ideas?
Looks like this is your problem:
$hoy = date('YYYY-MM-DD');
If you want to generate a date like 2015-12-02, you should do this instead:
$hoy = date('Y-m-d');
Source: http://php.net/manual/en/function.date.php
This query expects both conditions to be true.
If you want to return when either one is true you should try ->orwhere.
If you are looking for both to be true you need to keep in mind that if there are timestamps on the date the query of <= will only find dates with a timestamp of 00:00:00 for the requested date.