Trouble with AND operator on Eloquent Raw query MySQL JSON - mysql

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.

Related

how to search by letter in column in database (laravel)

I want to find by letter customer's first_name on my 'customers' table.
And the only thing that I get is an empty array.
For instance, I put in the parameter 'q' value 'E' to get customer Elena from my database by I get an only empty array.
I use the following code to get first_name :
$search = Input::get('q');
if($search)
{
$customers = Customer::all()->where('full_name', 'LIKE', "%{$search}%");
return ($customers);
}
Can someone help me?
Your query don't work because you are calling the all() method before the where(). That's actually not wrong, but it have different behavior.
When you call all(), it actually does the SQL query. After that, any chained methods are being called into a Eloquent Collection class, and it also have a where method, but that's simpler since it runs on PHO instead of running on SQL.
Since the collection's where() method doesn't support LIKE operator, it's probably searching for a value that is exactly %E%.
Hope it can help you understanding why your query doesn't work as expected.
Try this
$customers = Customer::where('full_name', 'LIKE', "%{$search}%")->get();
Laravel Eloquent

Laravel: using WHERE CONCAT in query

I am pretty new to laravel and facing a problem building a query using CONCAT:
#From input
$password = $request->password;
#sql statement
UserMainTbl::where('username', '=', $username)->whereRaw('hashkey', '=', CONCAT('admin_id'.$password))
Table: UserMainTbl
Field: username, hashkey, admin_id
Got error:
Call to undefined function App\Http\Controllers\Auth\CONCAT()
------
Update:
I change my code and manage to stop the above error. But getting new error.
->where('hashkey', '=', DB::raw('concat(admin_id,"$password")'))
Column not found: 1054 Unknown column 'password123' in 'where clause' (SQL: select * from user_main_tbl where username = xxx and hashkey = concat(admin_id,password123) limit 1)
------
Update [Solve]:
My bad on this one. It is just a simple string. Here is the solution for future reference, if any. Lol:
->where('hashkey', '=', DB::raw('concat(admin_id,"'.$password.'")'))
Can someone help to point how can I do it right?
Many thanks.
I know you have solved the issue, but your solution can open up possibilities for SQL Injection if you don't escape the user input.
One way to tackle this is by adding a binding.
UserMainTbl::where('username', '=', $username)
->where('hashkey', '=',DB::raw('concat(admin_id,"?")'))
->addBinding($password);
https://laravel.com/docs/5.3/queries#raw-expressions
Always be careful in using RAW method in query builder since it's prone to SQL injections. I suggest to separate the concatenation of the "admin_id" and "password" and use the standard WHERE method to avoid the problem.

cakephp3 clause where doesn't work

the code below is executed but it brings a wrong records(all records in my table) , it's like he doesn't take on consideration the clause where
$result = $this->Posts->query('SELECT * FROM POSTS WHERE id=1');
I know that I can do it easily with find() but for some reasons I want to write the sql statement and to have the right results
Thanks for helping me.
query() method does not take any parameter. you can use it like
$data= $this->Posts->query()
->where(['id'=>1])
->execute()
->fetchAll();

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)');

Using a table-alias in Kohana queries?

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.