Codeigniter query builder disable quotes - codeigniter

I am using Query builder on CodeIgniter 3. with Oracle DB.
I cannot create normal query. My query is:
$CI->db->query('c.*',false);
$CI->db->from('COUNTRIES c',false);
$CI->db->join('FILIALS as f','f.country_id=c.country_id',false);
$CI->db->where('f.FILIAL_ID',$id,false);
$query=$CI->db->get();
return $query->result('Country')[0];
This gives me a query
SELECT c.* FROM "COUNTRIES" "c" JOIN "FILIALS" as "f" ON "f"."country_id"="c"."country_id" WHERE f.FILIAL_ID = 7
But this query does not work, complaining that query is not correct. In Sqlplus the same problem.
But if I manually run in sqlplus,removing "as", and quotes in table fields and table names, it works normal.
This is my working query:
SELECT c.* FROM "COUNTRIES" c JOIN "FILIALS" f ON f.country_id=c.country_id WHERE f.FILIAL_ID = 7
How can I tell Query Builder, remove "as", and quotataion marks in query.

Try This Query :
$this->db->select('c.*',false);
$this->db->from('COUNTRIES c',false);
$this->db->join('FILIALS as f','f.country_id=c.country_id',false);
$this->db->where('f.FILIAL_ID',$id,false);
$query = $this->db->get();
return $query->result();

Remove AS from join
I thik its done.
$this->db->select('c.*',false);
$this->db->from('COUNTRIES c',false);
$this->db->join('FILIALS f','f.country_id=c.country_id',false);
$this->db->where('f.FILIAL_ID',$id,false);
$query = $this->db->get();
return $query->result();

Related

How to convert Sql query to codeigniter Active Record

I have sql query as below, i need to convert sql to codeigniter active record.
select * from color c
left join (select pc.* from product_color pc
LEFT join product p on pc.product_id=p.product_id
WHERE p.product_id=1)x on c.id=x.color_id
In codeigniter you can get compiled query using get_compiled_select function.
Let's create inner query first.
$inner_query = $this->db->select('pc.*')
->from('product_color pc')
->join('product p','pc.product_id = p.product_id','left')
->where('p.product_id',1)
->get_compiled_select();
Now we will use inner query to create our final query.
$final_query = $this->db->select('*')
->from('color c')
->join("($inner_query) x",'c.id=x.color_id','left')
->get_compiled_select();
echo $final_query; die;
Try this into model file. and it's always better to keep sql keywords in capital.
$query = "SELECT * FROM color c
LEFT JOIN (SELECT pc.* FROM product_color pc
LEFT JOIN product p ON pc.product_id=p.product_id
WHERE p.product_id=1)x on c.id=x.color_id"
$query = $this->db->query($query);
$data = $query->result_array();

GraphQL Where Select Sub Query

These day, i have studied GraphQL with Laravel framework, Lighthouse Library.
I have tried to do kind of SELECT Query.
As a result, I wonder GraphQL can select below SQL Query
SELECT * FROM TABLE_A WHERE type=1 AND chart_id=(SELECT id FROM TABLE_B WHERE phone='0000~~')
I expect, Client first get result from this query.
SELECT id FROM TABLE_B WHERE phone='0000~~'
And then Do Second query, i think i can get a result.
But i wonder I can get result from 1 request. Thanks.
You can try following
$phoneNumber = '0000~~';
$data = DB::table('tableA')->where('type',1)
->whereIn('chart_id',function($query) use ($phoneNumber) {
$query->select('id')
->from('tableB')
->where('phone', '=',$phoneNumber);
})->get();
If there is relationship between tableA and tableB you can do following
TableA::where('type',1)
->whereHas('tableBRelationshipName', function ($q) use ($phoneNumber) {
$q->select('id')
$q->where('phone','=',$phoneNumber);
})->get();

Converting a raw query to Laravel query builder

I have the following MySQL query which fetches a list of the last 9 authors to write a post and lists them in order of the date of the last post they wrote.
It's working properly but I'd like to re-write it using the Laravel Query Builder. Here is the query at the moment:
$authors = DB::select("
SELECT
`a`.`id`,
`a`.`name`,
`a`.`avatar`,
`a`.`slug` AS `author_slug`,
`p`.`subheading`,
`p`.`title`,
`p`.`slug` AS `post_slug`,
`p`.`summary`,
`p`.`published_at`
FROM
`authors` AS `a`
JOIN
`posts` AS `p`
ON `p`.`id` =
(
SELECT `p2`.`id`
FROM `posts` AS `p2`
WHERE `p2`.`author_id` = `a`.`id`
ORDER BY `p2`.`published_at` DESC
LIMIT 1
)
WHERE
`a`.`online` = 1
ORDER BY
`published_at` DESC
LIMIT 9
");
I understand the basics of using the query builder, but there doesn't appear to be anything in the Laravel docs that allows for me to JOIN a table ON a SELECT.
Can anyone suggest a way that I can write this query using the Laravel Query builder, or perhaps suggest a way that I can rewrite this query to make it easier to structure with the query builder?
Try to do like this
$data = DB::table('authors')
->select(
'a.id',
'a.name',
'a.avatar',
'a.slug AS author_slug',
'p.subheading',
'p.title',
'p.slug AS post_slug',
'p.summary',
p.published_at')
->from('authors AS a')
->join('posts AS p', 'p.id', '=', DB::raw("
(
SELECT p2.id FROM posts AS p2
WHERE p2.author_id = b.id
ORDER BY p2.published_at
DESC LIMIT 1
)"))
->where('a.online', 1)
->limit(9)
->orderBy('p.published_at', 'desc')
->get();

Using Mysql WHERE IN clause in codeigniter

I have the following mysql query. Could you please tell me how to write the same query in Codeigniter's way ?
SELECT * FROM myTable
WHERE trans_id IN ( SELECT trans_id FROM myTable WHERE code='B')
AND code!='B'
You can use sub query way of codeigniter to do this for this purpose you will have to hack codeigniter. like this
Go to system/database/DB_active_rec.php
Remove public or protected keyword from these functions
public function _compile_select($select_override = FALSE)
public function _reset_select()
Now subquery writing in available
And now here is your query with active record
$this->db->select('trans_id');
$this->db->from('myTable');
$this->db->where('code','B');
$subQuery = $this->db->_compile_select();
$this->db->_reset_select();
// And now your main query
$this->db->select("*");
$this->db->where_in("$subQuery");
$this->db->where('code !=', 'B');
$this->db->get('myTable');
And the thing is done. Cheers!!!
Note : While using sub queries you must use
$this->db->from('myTable')
instead of
$this->db->get('myTable')
which runs the query.
Watch this too
How can I rewrite this SQL into CodeIgniter's Active Records?
Note : In Codeigntier 3 these functions are already public so you do not need to hack them.
$data = $this->db->get_where('columnname',array('code' => 'B'));
$this->db->where_in('columnname',$data);
$this->db->where('code !=','B');
$query = $this->db->get();
return $query->result_array();
Try this one:
$this->db->select("*");
$this->db->where_in("(SELECT trans_id FROM myTable WHERE code = 'B')");
$this->db->where('code !=', 'B');
$this->db->get('myTable');
Note: $this->db->select("*"); is optional when you are selecting all columns from table
try this:
return $this->db->query("
SELECT * FROM myTable
WHERE trans_id IN ( SELECT trans_id FROM myTable WHERE code='B')
AND code!='B'
")->result_array();
Is not active record but is codeigniter's way http://codeigniter.com/user_guide/database/examples.html
see Standard Query With Multiple Results (Array Version) section
you can use a simpler approach, while still using active record
$this->db->select("a.trans_id ,a.number, a.name, a.phone")
$this->db->from("Name_Of_Your_Table a");
$subQueryIn = "SELECT trans_id FROM Another_Table";
$this->db->where("a.trans_id in ($subQueryIn)",NULL);

Getting results form a query to insert in other using active records

I'm needeing to get all the child categories from the given to use in a where_in with active records of codeigniter.
The problem is that the second query get mixed with the main one breaking it completely.
Main Query
$this->db->select('artworks.*, users.id as owner, users.name as user_name');
$this->db->from('artworks');
$this->db->join('users', 'users.id = artworks.user_id');
$category = $this->get_child_categories($this->get_categories(), $matches[1]);
$this->db->where_in('artworks.category', $this->category['child']);
$this->db->group_by('artworks.id');
$query = $this->db->get();
return $query->result_array();
Second Query "get_categories()"
$this->db->select('*');
$this->db->order_by('parent', 'asc');
$this->db->order_by('name', 'asc');
$query = $this->db->get('categories');
return $query->result_array();
get_child_categories
function get_child_categories($categories, $parent){
foreach($categories as $category){
if($category['parent'] == $parent){
array_push($this->category['childs'], $category['id']);
$this->get_child_categories($categories, $category['id']);
}
}
}
But i'm getting this error where clearly displays that the second query is quetting inside the main one.
Error Number: 1064
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '* FROM (`artworks`, `categories`) JOIN `users` ON `users`.`id` = `artworks`.`use' at line 1
SELECT `artworks`.*, `users`.`id` as user_id, `users`.`name` as user_name, * FROM (`artworks`, `categories`) JOIN `users` ON `users`.`id` = `artworks`.`user_id` WHERE `artworks`.`rating` IN ('g', 'm', 'a') ORDER BY `artworks`.`id` desc, `parent` asc, `name` asc
Filename: D:\Server\htdocs\gallery\system\database\DB_driver.php
Line Number: 330
I personally think this is an error in CodeIgniter's Active Record approach, if it's supposed to follow the Active Record pattern at all. It should totally enforce either one of these:
queries contained in a single data context
queries specified in a atomic instruction
As neither of these is happening, at the moment you're unwillingly mixing two queries with a structure that CodeIgniter does not support, thus creating that invalid query.
For a simple solution, I would suggest for you to invert the order of the instructions so that the queries are executed separately.
$category = $this->get_child_categories($this->get_categories(), $matches[1]);
# the first query gets executed here, your data context is cleaned up
$this->db->select('artworks.*, users.id as owner, users.name as user_name');
$this->db->from('artworks');
$this->db->join('users', 'users.id = artworks.user_id');
$this->db->where_in('artworks.category', $this->category['child']);
$this->db->group_by('artworks.id');
$query = $this->db->get();
# your second query gets executed here
return $query->result_array();

Resources