I Need to check if a variable is present inside a comma separated string in mysql field using querybuilder.
I do this
<?php
$parents = DB::table('categorie')>whereRaw('FIND_IN_SET("$categoria->id", parent)')->get();
but didn't return any value.
You should never put variables in the query yourself. Use bindings instead, this will make sure your parameters are correctly escaped.
<?php
$parents = DB::table('categorie')->whereRaw('FIND_IN_SET(?, parent)', [$categoria->id])->get();
You may debug the query using toSql() method after your query, which becomes
DB::table('categorie')->whereRaw('FIND_IN_SET("$categoria->id", parent)')->toSql();
This will clear it out if $categoria->id is being put in the query or not.
I can't comment yet, hence posting it as an answer.
Related
I need to eliminate the specific prefix of a string by default on getting value from the database.
In MySQL, i can use the following,
SELECT RIGHT('abc3',1) -- Results in "3"
SELECT RIGHT('abc3',2) -- Results in "c3"
But, how can i use same process in Laravel eloquent?.
Or any other solutions are available for remove the prefix of a string while retrieve from database in laravel.
I know trim will eliminate, but only spaces.
ex.
property_color
property_size
Here i need to extract "property_".
expect.
color
size
Is it possible in laravel, in without using PHP String function.
Only on Direct eloquent Operation.
Thanks in Advance !
That's what I would do:
$arrayData = DB::select(DB::raw("SELECT RIGHT('abc3',1) ")):
you can pass array of parameter to bind values:
DB::select(DB::raw(" SQL QUERY "),$paramsArray);
You have to use raw queries within your builder like
$results = YourRepo::where(DB::raw("SELECT SUBSTRING('property_color',9)") , 'LIKE', "%property_xxx%");
keep in mind that substring is slow.
How can I do multiple wherein in laravel?
$devices = DB::table('foo')
->select('foo.*')
->whereIn('bar1', $request->bar1)
->whereIn('bar2', $request->bar2)
->get();
Above is my sample code but it is returning me an empty array.
It is ok to use multiple WHERE IN constraints in your query. The code you provided is also ok.
If you're getting no results, make sure that values of $request->bar1 and $request->bar2 are what you expect - they should be arrays of values that contain what you want your bar1/bar2 columns to be.
You can always get the generated SQL by calling toSql() instead of get(), you can also inspect the values of parameters by calling getBindings().
In CakePHP3, there is a ORM that helps with building queries.
From the documentation, I can see that
$query = $articles->find(); // build a query that has not run yet
$query->where(['id' => 1]); // Return the same query object
So in this case, I want the string
WHERE `articles`.`id` = 1
After much googling, I found out that there is a way to return just the where clause of a query object.
$query->where(['id' => 1])->clause('where'); // Return the where clause in the form of a QueryExpression
More googling leads me to find out how to get the QueryExpression to spit out string representation
$query->where(['id' => 1])->clause('where')->sql($valueBinder); // Return the where clause in string format
Here is my problem. I don't know what the $valueBinder is supposed to look like. I don't know how to initialize it.
I am also happy not to use ValueBinder as long as I can get the where clause in string format using CakePHP 3 ORM and in the right SQL dialect. Please assume I am using MySQL.
Please advise.
EDIT
I tried to use $query->valueBinder() as the $valueBinder.
It is empty and does not contain the associated c:0 to the value 1.
To directly answer your question, you can get the SQL for any clause this way:
$binder = new \Cake\ORM\ValueBinder();
$query->clause('where')->sql($binder);
That will return the SQL with the correct placeholders, not with the values to be used. The values live in the $binder variable and are used for statement objects.
As I can see, you only wanted to preserve the internal structure of the where clause to pass it to another query in a different request. Your solution is fine, but I'd like to add that you can also encode a full conditions tree from an existing query:
$where = serialize($query->clause('where'));
$anotherQuery->where(unserialize($where)); // A query in another request
In any case, you need to be careful with what you are unserializing as taking it directly from user input will certainly lead to security problems.
You can choose to omit this param if you like. Please see http://api.cakephp.org/3.0/class-Cake.Database.Query.html#_sql
In addition, you can use the Query member function traverse($visitor, $parts) to isolate the where clause. $visitor is a function that takes a value and a clause. You define the behavior of $visitor. $parts is an array of clause names. I suggest passing array('where') into this param.
My workaround is that I store the conditions in json string format.
Using the same example, what I do is
$data['conditions'] = json_encode(['Articles.id' => 1]); // encode into JSON string
$this->DynamicRules->patchEntity($dynamicRule, $data); // use in edit action of DynamicRulesController
then when I need to reuse the conditions, I do:
$articlesTable = TableRegistry::get('Articles');
$query = $articlesTable->find(); // new query for Articles
$rule = json_decode($dynamicRule->conditions, true); // get back the conditions in associative array format
$query->where($rule); // re-assign the conditions back
This got me what I ultimately wanted.
For my database query I have to use multiple where clause query in Codeigniter PHP. I wrote the code like this:
$this->db->and_where_in('category_name,publication_status','home_headline_sub',1);
But this query shows database query error in browser. Then I wrote this query:
$this->db->where('category_name,publication_status','home_headline_sub',1);
But it still give error. Can anyone help me to solve this? Thanks in advance.
You can chain database clauses, so you would write it as
$this->db->where('category_name','case')->where('publication_status','case')->where('home_headline_sub','case');
This would generate a query's WHERE clause as
// WHERE category_name = 'case' AND publication_status = 'case' AND home_headline_sub = 'case'
Documentation here: http://ellislab.com/codeigniter/user-guide/database/active_record.html#chaining
you to use array in it.
$this->db->where(array('category_name'=>case,'publication_status'=>case,'home_headline_sub'=>case));
but I guess you want to check your value against three columns. you can use
$this->db->or_where(array('category_name'=>1,'publication_status'=>1,'home_headline_sub'=>1));
I hope it will help you.
//The simple way
$this->db->where('foo_field', 'foo_value')
->where('bar_field', 'bar_value')
->where('more_field', 'more_value');
//using custom string
//if your sql is really a complex one you can simply write like these
$this->db->where("(foo_filed = 'foo_value') AND (bar_field = 'bar_value') AND (more_field = 'more_value')");
//or may be with something more complex like this
$this->db->where("(foo_filed = 'foo_value') AND ((bar_field = 'bar_value') OR (more_field = 'more_value'))");
//while using a custom string make sure you put them all in the "double quotation marks" and use no ,commas. It is all a single line. The braces are not necessary always but I like to use them.
Documentation
I want to use a single query to retrieve:
items of any categories (no filter applied);
only items of a single category (limited to a particular category);
For that purpose I should be able to write a Doctrine query which would include a where clause only when certain condition is met (eg. part of URL existing), otherwise, where clause is not included in the query.
Of course, i tried with using the If statement, but since doctrine query is chained, the error is thrown.
So i guess the solution might be some (to me unknown) way of writing doctrine queries in an unchained form (by not having each row started with "->" and also having each row of a query ending with semicolon ";")
That way the usage of IF statement would be possible i guess.
Or, maybe there's already some extremely simple solution to this matter?
Thanks for your reply!
I am unfamiliar with Codeigniter but can't you write something like this?
$q = Doctrine_Query::create()
->from('items');
if ($cat)
$q->where('category = ?', $cat);
In your model pass the condition for where as a parameter in a function.
In below example i am assuming the function name to be filter_query() and passing where condition as a parameter.
function filter_query($condition=''){
$this->db->select('*');
$this->db->from('TABLE NAME');
if($condition != ''){
$this->db->where('condition',$condition);
}
}
In above example i have used Codeigniter's Active Record Class.