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]
]);
Related
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]
]);
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();
I am trying to delete data from RestoFoods model like that:
RestoFoods::deleteAll(["restaurant_id"=>$postData['resto_id'], 'food_id NOT IN'=> [1,2] ]);
I want this sql:
DELETE FROM `resto_foods` WHERE `restaurant_id`=1 AND (`food_id` NOT IN (1, 2));
You can try this way
RestoFoods::deleteAll(['AND', 'restaurant_id = :restaurant_id', ['NOT IN', 'food_id', [1,2]]], [':restaurant_id' => $postData['resto_id']]);
Output for this will be you want:
DELETE FROM `resto_foods` WHERE (restaurant_id = 1) AND (`food_id` NOT IN (1, 2));
Is it possible to make a multilevel array using a mysql query? E.g. if I want to get 4 pictures for each product?
[1] => Array( 'name' => 'Product 1', 'picture' => array('picture1','picture2','picture3','picture4') )
[2] => Array( 'name' => 'Product 2', 'picture' => array('picture5','picture6','picture7','picture8') )
Or do I need to make a foreach to loop through the products and then in the foreach make a mysql query to get each products pictures?
EDIT:
My structure is:
P_Attributes
--------
id, int(15)
name, varchar(256)
P_AttributeValues
--------
id, int(15)
value, varchar(256)
attribute_id, int(15) [NOTE: This is connected to P_Attributes.id]
Then I want to get ALL P_AttributeValues to a P_Attribute row - and get it in ONE query. Is that possible?
EDIT 2:
With the query made by the accepted answers author I made it work with this PHP-code:
$attributevalues = $auctionClass->get_rows($id);
$attr_val = array();
foreach($attributevalues as $k => $v){
$attr_val[$v->AID]['attr_name'] = $v->AName;
$attr_val[$v->AID]['parameters'][] = array('attr_value_name' => $v->name, 'id' => $v->id);
}
Here is a good article on doing this type of query:
http://www.xaprb.com/blog/2006/12/07/how-to-select-the-firstleastmax-row-per-group-in-sql/
You might be able to adjust their examples to fit your needs.
If you just use a normal JOIN query and order it, you can get rows coming out of the records that can be formed in to the necessary hierarchical structure.
SELECT pa.id AS product_id, pa.name , pav.id AS product_attr_id, pav.value
FROM P_Attributes pa JOIN P_AttributeValues pav ON pav.attribute_id = pa.id
ORDER BY pa.id ASC, pav.id ASC
This will generate rows like this:
product_id, name, product_attr_id, value
1, "Product 1", 1, "picture1"
1, "Product 1", 2, "picture2"
1, "Product 1", 3, "picture3"
1, "Product 1", 4, "picture4"
2, "Product 2", 5, "picture5"
2, "Product 2", 6, "picture6"
2, "Product 2", 7, "picture7"
2, "Product 2", 8, "picture8"
No idea what MySQL extension you are using, presumably PHP as I mentioned it and you didn't correct me. If you fetch the associative array per record returned, which will be, per record, in this form:
array('product_id' => 1, 'name' => "Product 1",
'product_attr_id' => 1, 'value' => "picture1");
If you have a main data array called $products, you can produce it by just putting this code in the loop, assuming the record is called $productRec and filled in the loop before this.
if (!array_key_exists($productRec['product_id'], $products)) {
$products[$productRec['product_id']] = array('name' => $productRec['name'],
'picture' => array());
}
$products[$productRec['product_id']]['picture'][$productRec['product_attr_id']] =
$productRec['value'];
Using the IDs for the keys should be alright, presuming that they are primary keys with no duplicates. Will aid look up that way, rather than losing that data.
Depending on your table structure, you may be able to pull rows that have everything you're looking for, and then code the creation of the array from that row.
Does $this->db->insert_batch(); insert with 1 table connection or does it insert each row separately incurring overhead of opening connections?
From the documentation of code igniter insert_batch do this kind of things
$data = array(
array(
'title' => 'My title' ,
'name' => 'My Name' ,
'date' => 'My date'
),
array(
'title' => 'Another title' ,
'name' => 'Another Name' ,
'date' => 'Another date'
)
);
$this->db->insert_batch('mytable', $data);
// Produces: INSERT INTO mytable (title, name, date) VALUES ('My title', 'My name', 'My date'), ('Another title', 'Another name', 'Another date')
So it would produce only one query with all the values, normally this way faster then doing separate inserts.
To answer your question: It uses one connection.
Actually #RageZ answer based on document is not always correct. Because it's totally based on the number of items you want to insert. When looking at codeigniter insert_batch() code, you can see that they slice batch inserts into 100 items.
// Batch this baby (Around line number 1077 in codeigniter 2.x)
for ($i = 0, $total = count($this->ar_set); $i < $total; $i = $i + 100)
{
$sql = $this->_insert_batch($this->_protect_identifiers($table, TRUE, NULL, FALSE), $this->ar_keys, array_slice($this->ar_set, $i, 100));
//echo $sql;
$this->query($sql);
}
It means that your values will be slice to 100s inserts and if you uncomment the echo $sql part you can see what it's look like when you use insert batch for 101 items. So based on your connection preferences there can be more than one connection needed for inserting in db.