Using a table-alias in Kohana queries? - mysql

I'm trying to run a simple query with $this->db in Kohana, but am running into some syntax issues when I try to use an alias for a table within my query:
$result = $this->db
->select("ci.chapter_id, ci.book_id, ci.chapter_heading, ci.chapter_number")
->from("chapter_info ci")
->where(array("ci.chapter_number" => $chapter, "ci.book_id" => $book))
->get();
It seems to me that this should work just fine. I'm stating that "chapter_info" ought to be known as "ci," yet this isn't taking for some reason. The error is pretty straight-forward:
There was an SQL error: Table 'gb_data.chapter_info ci' doesn't exist -
SELECT `ci`.`chapter_id`, `ci`.`book_id`, `ci`.`chapter_heading`,
`ci`.`chapter_number`
FROM (`chapter_info ci`)
WHERE `ci`.`chapter_number` = 1
AND `ci`.`book_id` = 1
If I use the full table name, rather than an alias, I get the expected results without error. This requires me to write much more verbose queries, which isn't ideal.
Is there some way to use shorter names for tables within Kohana's query-builder?

In Kohana 3 it is simply enough:
->from( array('table_name', 'alias') )
and this will create the query that contains:
FROM 'table_name' AS 'alias'
I have tested it and it works. Good luck.

$result = $this->db
->select("ci.chapter_id, ci.book_id, ci.chapter_heading, ci.chapter_number")
->from("'chapter_info' AS ci")
->where(array("ci.chapter_number" => $chapter, "ci.book_id" => $book))
->get();
That should work. As you must wrap the original table name in quotes first before the AS keyword and the new table name you want to shorten it to.

Try using the "as" keyword like ->from("chapter_info as ci"), maybe the query builder will recognize it this way.

Related

Trouble with AND operator on Eloquent Raw query MySQL JSON

I am trying to figure out the correct syntax to add an AND operator to the following Eloquent Raw query in which I am querying a MySQL (5.7.9) table's JSON field. In doing so, I would like to be able to have case insensitivity capabilities.
After doing initial research as to how to achieve this, I have my code working in a basic way like this:
$users = User::whereRaw('lower(info_json->"$.full_name") like lower(?)', ["%{$user_name}%"])
But my goal is to add an AND operator to narrow down my results further with a non-JSON varchar column.
I have tried this (and other variations without success):
$users = User::whereRaw('lower(info_json->"$.full_name") like lower(?)', 'and user_type = admin', ["%{$user_name}%"])
Which gives me an error:
"Array to string conversion"
I have also tried:
$users = User::whereRaw('lower(info_json->"$.full_name") like lower(?) and user_type = admin', ["%{$user_name}%"])
Which give me the following error:
"SQLSTATE[42S22]: Column not found: 1054 Unknown column 'user_type' in 'where clause'"
Other similar variations that have not resulted in errors have yielded too many or too few results.
How can I successfully adjust my syntax to query an additional non-JSON field with the correct results? Also, is doing a raw query like this the most effective way to do so with Eloquent, MySQL (5.79) and Laravel 5.6?
Thank you for any and all help/direction offered! :)
I think you should do something like
$users = User::where(DB::raw('lower(info_json->"$.full_name")', 'like', DB::raw('lower(%{$user_name}%)'))
->where('user_type', '=', 'admin')
Probably I have some sintax error but main idea is to use DB::raw to help you with your query.
I figured it out. My syntax should have looked like this:
$users = User::whereRaw('lower(info_json->"$.full_name") like lower(?)', ["%{$user_name}%"])->where('user_type', '=', 'admin')->get();
Thanks to those who assisted with this! Like a lot of syntax/coding problems, taking a little break from it helped me to figure it out quite quickly when I returned to it.

How to query the DB to find an element inside a column that contain a json data from a multi select (Laravel)

This is what I've in my "attrib" db column data:
["last","featured","disabled"]
I try to add in my query something like
->whereRaw('FIND_IN_SET(?,attrib)', ['featured'])
but it not works...
UPDATE
I've resolved with:
$featured = Course::where('attrib', 'like', '%featured%')->get();
But I'm still looking for a better query without the use of "LIKE".
You may use whereIn() in your model
$attrib=["last","featured","disabled"];
->whereIn('attrib',[$attrib])->get();

Symfony 2 - Doctrine ORM Update query not working

I am trying to update a mysql table with following query using Doctrine. But the table is not get updated. Also below code didnt throw any error. I am totally confused. If i run the query, taken from getDQL() method, in mysql directly it showing 0 rows updated becuase of inproper qoutes. it is working after placed proper qoutes for values in the query. Need help to solve this puzzle.
Since i am new to doctrine, i will use the examples give in querybuilder class file.
$support = $this->createQueryBuilder('p')
->update('gcns', 'g')
->set("g.isActive", "0")
->andWhere("g.issn='".$issn."'");
Do you ever execute the query or are you just building it? You should have something along these lines to execute it:
$support->getQuery()->getSingleScalarResult();
If i run the query, taken from getDQL() method, in mysql directly it showing 0 rows updated becuase of inproper qoutes.
getDQL() returns DQL not SQL, so it will have improper quotesif you try to run it directly inside MySQL, but that's expected.
You shouldn't concatenate $issn into your query. You should use parameters instead:
$qb = $this->createQueryBuilder()
$support = $qb->update('gcns', 'g')
->set('g.isActive', '0')
->andWhere( $qb->expr()->eq('g.issn', ':issn') )
->setParameter( 'issn', $issn )
->getQuery()->getSingleScalarResult()
;

Laravel query build based on relation

I have such query:
Tournament::has('participations', '<', '2')->get();
How can I replace constant number '2' on tournament's column named slots ?? I would like retrieve only these tournaments which have least participants than slots in tournament.
Let's start by using the column name instead of "2". Like you would do in "normal" SQL
Tournament::has('participations', '<', 'slots')->get();
Now, you don't even have to try that because it won't work. But why's that? Because Laravel treats slots like a string and escapes it so SQL does as well.
What you need to do, is use DB::raw(). raw makes sure Laravel changes nothing and just injects it into the SQL query
Tournament::has('participations', '<', DB::raw('slots'))->get();
Update
After some trying out I found this: (Its not very pretty but the only way I got it working)
$subquery = function($q) use ($uid){
$q->where('player_id', $uid);
}
Tournament::whereHas('participations', $subquery)
->whereHas('participations', $subquery, '<', DB::raw('slots'))
->get();
The first whereAs checks for count(*) > 0, the second count(*) < slots and the subquery filters by player id.

how to get Even/Odd id numbers from a database table in codeigniter

I am new in codeigniter and just stacked in a query to solve a report for an emergency project. Please help me Codeigniter's Experts.
I have a large database table and wants to show only Odd/Even Data rows from that table which will filtered by a table Field named is "sale_id". I tried it in PHPMyadmin in raw coding and it's worked for me. But can not apply in Codeigniter.
SELECT * FROM ospos_pak_sub_cat WHERE id %2 =0;
Worked for me in raw PHP Coding. How can I use it in Codeigniter. I used a Where Condition already on that query and now want to add the new query.
Existing Where condition is given below, which is working fine.
$this->db->where('sale_date BETWEEN "'. $inputs['start_date']. '" and "'. $inputs['end_date'].'"');
It is working and I tried the code below to get the solution which is not working and getting error.
$this->db->where('sale_id %2'=> 0);
Getting error with this line. says--
Parse error: syntax error, unexpected '=>' (T_DOUBLE_ARROW)
Please help me to get the solutions. Thanks in Advance.
In your Model, just write the query like that:
$this->db->select('*');
$this->db->from('ospos_pak_sub_cat');
$this->db->where('sale_id %2=', 0);
$query_result = $this->db->get();
$result = $query_result->result();
You missed the '=' in your code. Hope, it will work.
in SQL the % character is a wildcard rather than a modulo which would explain your error. you can use the MOD function instead http://dev.mysql.com/doc/refman/5.0/en/mathematical-functions.html#function_mod
so the resulting code would be :
$this->db->where('MOD(sale_id ,2) => 0');
I am not sure but i think it will work try this line
$this->db->where('sale_id %2',0);
As you mentioned, you can add the new condition in existing where condition as like below
$this->db->where('(sale_date BETWEEN "'. $inputs['start_date']. '" and "'. $inputs['end_date'].')" and ((sale_id % 2) = 0)');