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));
Related
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]
]);
DB::table('my_table')->insertGetId([
...
'code' => $data['code'],
'geopoint' => \DB::raw('POINT(?, ?)', [$data['lat'], $data['lng']]),
...
]);
it returns
Invalid parameter number (SQL: insert into `residence` (`code`, values (POINT(, ), , ?, ?)
How can I fix this?
Thanks
try this way
create array for the value you want to insert apply key same as field name in you table
$point = DB::select("SELECT POINT($data['lat'], $data['lng']) as point FROM `any_table_name_avilable_in_your_db` LIMIT 1");
$data=array(
"lat_field_name_table"=>$data['lat'],
"lng_field_name_table"=>$data['lng'],
"location"=>$point[0]->point
);
$checkinsert=DB::table('mytablename')->insert($data);
and check is your data inserted like this
if($checkinsert>0){
//data inserted
//do whatever you want if inserted
}else{
//data not inserted
//do whatever you want if not inserted
}
or in your way like this :
$point = DB::select("SELECT POINT($data['lat'], $data['lng']) as point FROM any_table_name_avilable_in_your_db LIMIT 1");
DB::table('my_table')->insertGetId([
...
'code' => $data['code'],
'geopoint' =>$point[0]->point ,
...
]);
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();
how can I select multiple or in codeigniter?
for exmaple, select * from bla where id = 1 or id = 2 or id = 3?
If I use this:
$this->db->where('name', $name);
$this->db->where('title', $title);
$this->db->where('status', $status);
it is with AND...
You can use the where_in method as a shortcut to multiple or-statements for the same column:
$available_ids = [1, 2, 3];
$this->db->where_in('id', $available_ids);
// WHERE id IN (1, 2, 3)
If you were looking to check multiple columns (the name is 'Adam' or the title is 'Grand Poobah' or the status is 'Active'), you can use the or_where method instead:
$this->db->where('name', $name);
$this->db->or_where('title', $title);
$this->db->or_where('status', $status);
// WHERE name = 'Adam' OR title = 'Grand Poobah' OR status = 'Active'
To put it all together, you'd
$available_ids = [1, 2, 3];
$query = $this->db->select('*')->from('bla')->where_in('id', $available_ids)->get();
// SELECT * FROM bla WHERE id IN (1, 2, 3)
CodeIgniter v3 Reference
CodeIgniter v2 Reference
Just try this
$array = array(
'name' => $name,
'title' => $title,
'status' => $status
);
$this->db->where($array);
Add all data to an array. Then pass the array to where clause.
I have a problem regarding merge of multiple queries.
In Yii 1.x you could merge a CDbCriteria with
$criteria->merge($otherCriteria)
How can I achieve the same nested conditions etc with queries in Yii2?
Edit:
Let's say I want separate queries to form subqueries. And after all subqueries are done I want to merge them together to the one big query.
There is no CDbCriteria concept in Yii2 anymore. Instead you can refer to the following classes:
http://www.yiiframework.com/doc-2.0/yii-db-query.html (yii\db\Query)
http://www.yiiframework.com/doc-2.0/yii-db-activequery.html (yii\db\ActiveQuery)
All you did before with CDbCriteria now you can do with above classes. So, there will be no need to merge two criteria with each other.
update
Yii2 also supports sub-queries like below (as Yii2's official guide):
$subQuery = (new Query)->select('COUNT(*)')->from('user');
$query = (new Query)->select(['id', 'count' => $subQuery])->from('post');
Which results in:
SELECT `id`, (SELECT COUNT(*) FROM `user`) AS `count` FROM `post`
http://www.yiiframework.com/doc-2.0/guide-db-query-builder.html#building-query
I also recently ran into this issue. Complete fusion of queries (select, join etc.) does not exist (as I understand it). But you can manually merge conditions, for example:
$query1 = \app\models\User::find()
->where(['column1' => 'value1', 'column2' => 'value2']);
$query2 = \app\models\User::find()
->where(['and', '[[column3]] = :column3', '[[column4]] = :column4'])
->addParams([
':column3' => 'value3',
':column4' => 'value4'
]);
// merge conditions
$query1->orWhere($query2->where);
$query1->addParams($query2->params);
// build SQL
echo $query1->createCommand()->rawSql;
Built SQL:
SELECT * FROM `yii2_user` WHERE
((`column1`='value1') AND (`column2`='value2')) OR
((`column3` = 'value3') AND (`column4` = 'value4'))
In addition to both the excellent answers above, should you need to merge two conditions to send on to a method which takes a 'condition' parameter in the same format as where(), then you can either build your own array:
$condition1 = ['column1' => 'value1', 'column2' => 'value2'];
$condition2 = ['column3' => 'value3', 'column4' => 'value4'];
$condition = [
'or',
$condition1,
$condition2,
];
$model->updateAll([ 'column5' => 'value5' ], $condition);
Or, if it feels more logical, you can use a temporary query object to build the conditions up and merge, etc. Then pass the generated where condition from it, e.g.:
$query1 = new \yii\db\Query;
$query1->andWhere(['column1' => 'value1', 'column2' => 'value2']);
$query2 = new \yii\db\Query;
$query2->andWhere(['column3' => 'value3', 'column4' => 'value4']);
$query = new \yii\db\Query;
$query->where($query1->where)
->orWhere($query2->where);
$model->updateAll([ 'column5' => 'value5' ], $query->where);
Obviously, this makes more sense when the queries or conditions are built up elsewhere in the code and separately passed the the place where the model method is executed.