Laravel: unable to build multiple orWhere query with laravel query builder - php

I am trying to make this query with laravel query builder but i did not understand how i can do this:
Query
select * from `data_table_1486794412` where (`column_2` = '2014' or `column_2` = '2015') and (`column_1` = 'GNDU')
My Code is:
$dbObj = DB::table($datatableName->dataset_table);
$dbObj->orWhere('column_2','2015');
$dbObj->orWhere('column_2','2015');
$dbObj->where(array('column_1','GNDU'));
Laravel Generating Query:
select * from `data_table_1486794412` where `column_2` = ? or `column_2` = ? and (`column_1` = ?)
My Table

In order to group WHERE clauses so that they're surrounded by brackets you need to pass a callback to where() call.
The following code should do the trick:
$dbObj = DB::table($datatableName->dataset_table);
$column1 = 2015;
$column2 = 2016;
$dbObj->where(function($query) use ($column1, $column2) {
$query->orWhere('column_1',$column1);
$query->orWhere('column_2',$column2);
});
$dbObj->where(array('column_1','GNDU'));

i think that's work
$dbObj = DB::table($datatableName->dataset_table);
$dbObj->orWhere('column_2','2015')->orWhere('column_2','2015')->where(array('column_1','GNDU'))

i am using orWhere in loop. can you please tell how i can use it in loop..because 2014 and 2015 are coming in form of array.
You can use whereIn rather than a loop, where you can pass in an array:
$dbObj = DB::table($datatableName->dataset_table);
$dbObj->where('column_1', 'GNDU')->whereIn('column_2', $yourArray)->get();

Related

How to search for 2 values in the same field with codeigniter?

I have a database field containing keyword ids ["1","2","3","4","5","6"] and I want to search for several of these ids in the same field.
Here is the idea of what I would like to achieve:
$tags[] = "\"1\"";
$tags[] = "\"2\"";
$query = $this->db->like(array('ids_keywords' => $tags[0], 'ids_keywords' => $tags[1]));
The problem here is that codeigniter only executes the last request instead of both because the search field is same.
What would be the best solution to do this?
try the following
$arrTags = [1,2];
$this->db->group_start()
foreach($arrTags AS $strTag)
{
$this->db->like(ids_keywords, '"'.$strTag.'"');
}
$this->db->group_end();
You can write your own clauses:
$where = "ids_keywords='1' AND ids_keywords='2' OR ids_keywords='3'";
$this->db->where($where);
For safe query use question mark(?)
$sql = "SELECT * FROM some_table WHERE ids_keywords = ? AND ids_keywords = ? AND ids_keywords = ?";
$this->db->query($sql, array(1, 2, 3));
In the above example, the question mark(?) will be replaced by the array in the second parameter of query() function. The main advantage of building query this way is that the values are automatically escaped which produce safe queries. CodeIgniter engine does it for you automatically.

In ci Where_in is not working properly

$menus = implode(',', $menu_id);
$this->db->where_in('rgroup_id',$menus);
$query = $this->db->get('rights_group');
please give me suggestion
Please check this code.
$menu_id = "1,2,3";
$menus = explode(',', $menu_id);
$this->db->where_in('rgroup_id', $menus);
$query = $this->db->get('rights_group');
You should use array as value try this
$menus = [1, 3, 4];
$this->db->where_in('rgroup_id', $menus);
$query = $this->db->get('rights_group');
more : https://codeigniter.com/user_guide/database/query_builder.html#CI_DB_query_builder::where_in
May be bug on Codeigniter,
I copy query and run on mysql and it has no error, but codeigniter still error near WHERE ... IN ()
So I run by native and it work like a charm.
$this->db->save_queries = TRUE;
$this->db->from('rights_group');
$query = $this->db->last_query();
return $this->db->query($query)->result();
Don't forget:
$this->db->save_queries = TRUE;
Change
$this->db->where_in('rgroup_id',$menus);
to
$this->db->where_in('rgroup_id',$menus,false);
Look at the generated query below.
SELECT * FROM `my_table` WHERE `my_id` IN(‘1,2,3’)
There is a quote before 1 and after 3. The query should be
SELECT * FROM `my_table` WHERE `my_id` IN(1,2,3)
to work it as expected.
We do not need to implode the array: directly pass array in where_in. You will get result. I have tried and it worked.

yii2 findAll not working passing in parameter from variable

I am trying to get the following query:
SELECT * FROM `book_category_tree` WHERE `id` IN (8, 9, 10, 15)
According the following yii2 documentation:
http://www.yiiframework.com/doc-2.0/yii-db-baseactiverecord.html#findAll%28%29-detail
If i use:
$rows = BookCategoryTree::findAll([8,9,10,15]);
It works perfect but when ever I try to use a variable with the values yii2 doesn't recognize the values:
$myValues = '8,9,10,15';
$rows = BookCategoryTree::findAll([$myValues]);
and generates the following query:
SELECT * FROM `book_category_tree` WHERE `id`='8,9,10,15'
I am getting crazy to avoid this I also tried:
$rows = BookCategoryTree::find()->where(['in','id',[$myValues]])->all();
But I have no luck.
Any ideas welcome,
Thanks
you should use where condition with operator notation like this
$rows = BookCategoryTree::find()->where( ['in', 'id', [8,9,10,15]])->all();
or
$myValues = [8,9,10,15];
$rows = BookCategoryTree::find()->where(['in','id',$myValues])->all();
if you have value in string you can use explode for build an array
$myValues =explode(',', $string_values);

How to implement "WHERE NOT IN" query into Codeigniter Active records?

I have a MySQL query which is this:
SELECT * FROM tbl_post WHERE tbl_post.post_id NOT IN
(SELECT tbl_readsave.post_id FROM tbl_readsave)
I want to convert it into Codeigniter Active records, so I used the following code segment:
$this->db->select('tbl_readsave.post_id');
$queryReadSave = $this->db->get('readsave');
$this->db->where_not_in('post_id', $queryReadSave->result_array());
$queryNewPost = $this->db->get('readsave');
if($queryNewPost->num_rows()>0)
{
return $queryNewPost->result_array();
}
else
return false;
However, the code throws me an error, which is like the following:-
Error Number: 1054
Unknown column 'Array' in 'where clause'
SELECT * FROM (`tbl_readsave`) WHERE `post_id` NOT IN (Array)
Filename: /var/www/html/teamF/tharjumal/models/webservice_model.php
Line Number: 28
How can I convert the above stated query into Codeigniter Active Records format?
$queryReadSave->result_array() returns an array of arrays. You can't use that in where_not_in.
You need to loop over that and create a flat array of the IDs you (don't) want.
$this->db->select('post_id');
$queryReadSave = $this->db->get('readsave');
$postIDs = $queryReadSave->result_array();
$this->db->where_not_in('post_id', array_column($postIDs, 'post_id'));
$queryNewPost = $this->db->get('post');
array_column() only exists in PHP 5.5+. If you are on a lower version, you'll need to do something like this:
$this->db->select('post_id');
$queryReadSave = $this->db->get('readsave');
$postIDs = array_map(function($a){
return $a['post_id'];
}, $queryReadSave->result_array());
$this->db->where_not_in('post_id', $postIDs);
$queryNewPost = $this->db->get('post');
P.S. Your second table is called post, right? You'll need to update the query to use the right table.
Update: Your original query uses a subquery which is not natively supported by CodeIgniter. If you want to try this all as one query, you can use the Subquery library I created (https://github.com/NTICompass/CodeIgniter-Subqueries).
$this->db->select('*');
$this->db->from('post');
$sub = $this->subquery->start_subquery('where_in');
$sub->select('post_id')->from('readsave');
$this->subquery->end_subquery('post_id', FALSE);
$queryNewPost = $this->db->get();
try below code:
$read_post_id = [];
$queryReadSave = $this->db->select('post_id')->get('tbl_readsave')->result_array();
if(count($queryReadSave) > 0){
foreach($queryReadSave as $row){
$read_post_id[] = $row['post_id']; // add each post id to the array
}
}
$this->db->select('*');
if(!empty($read_post_id)) $this->db->where_not_in('post_id',$read_post_id);
$post = $this->db->get('tbl_post');
print_r($post->result_array());
exit;

SELECT (COUNT(*)) query in ZF2

I'm trying to execute SQL query with table gateway which contain COUNT(*) expression in ZF2. This is function in my model:
public function brKomentariUred(){
$sql = $this->tableGateway->getSql();
$select = $sql->select();
$select->columns(array('brKomentari' => new \Zend\Db\Sql\Expression('count(komentarID)'), 'uredId' => 'ured'));
$select->group('ured');
//echo $sql->getSqlStringForSqlObject($select); die();
return $this->tableGateway->selectWith($select);
}
When the query is printed it is correct
SELECT count(komentarID) AS `brKomentari`, `komentar`.`ured` AS `uredId` FROM `komentar` GROUP BY `ured`
In the controller I'm trying to call the query with this code
foreach($this->getKomentarTable()->brKomentariUred() as $r){
$arr = $this->object_to_array($r);
print_r($arr);
}
It doesn't return number of elements and devicesID as it is written in SELECT, but return as SELECT * FROM komentar, but with no values. Is this right code or I'm making some error in my code? Other queries are OK.
Thanks in advance for your help.
In your place I would do the following steps:
replace the expression object with new \Zend\Db\Sql\Expression('COUNT(komentarID)')
I wouldn't use an alias in group by operator, it may not work. So,
replace this $select->group('ured') with
$select->group('komentar.ured')
Also, the result processing should be simplified:
$resultSet = $this->getKomentarTable()->brKomentariUred();
print_r($resultSet->toArray());

Categories