I fairly new to YII and still trying to understand it all. However from what I can tell when you do something like
yourModel->findAll(criteria)
Is like "Select * from"? or is it more like "Select yourModel->Attributes from"? In either case I was wondering in CDbCriteria is there a way to remove columns from the select. My case I have a user table that contains password I would like to prevent this from being added in the query.
Thanks,
Ofcourse you can select specific columns, just use the select property of CDbCriteria:
$criteria=new CDbCriteria();
$criteria->select='column1, column2';// or you can use array array('column1','column2')
$manymodels=$yourmodel->findAll($criteria);
So it is more like : "Select criteria->select from yourmodelclass' dbtable".
Note that findAll() will return you an array of models.
Related
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();
I'm totally new in yii2 and I want to know what does it mean the colon in the query?
I have made a research about binding parameters, but in the yii2 documentation says:
// returns all inactive customers
$sql = 'SELECT * FROM customer WHERE status=:status';
which side is from the data base? the left side or the right side?
which is a simple text and which one is a column from the DB? Im so confused.
what would be another way to make the query without the colon? is it valid?
why it has 'anyo = **:**valor' in the next example? and some others dont?
$dbLibro = Libro::find()->where('tipo = "Nacimiento"')->andWhere('cerrado = 0')->andWhere('anyo = :valor',[':valor'=>date("Y")])->one();
I hope its clear cause the documentation is a bit confusing for me.
The colons are not directly related with Yii2, it's related with PHP PDO extension that used by Yii2.
Each colon is placeholder used later for binding value. Check for example this question.
If we write this query in ActiveQuery:
SELECT * FROM customer WHERE status = :status
we can get something like this:
$query = Customer::find()->where('status = :status', [':status' => Customer::STATUS_ACTIVE]);
Assuming STATUS_ACTIVE constant equals to 1, after execution it transforms to this:
SELECT * FROM "customer" WHERE status = 1
So the left side (before equals) represents column name, right part - value which will be safely binded after.
But you don't have to write params by yourself, Yii2 QueryBuilder generates it automatically for you.
There are other ways to write query without colons and they are used more often. This query can be written like this:
$query = Customer::find(['status' => Customer::STATUS_ACTIVE]);
$models = $query->all();
Or like this using shortcut:
$models = Customer::findAll(['status' => Customer::STATUS_ACTIVE]);
Or it can be even put inside of a scope:
$models = Customer::find()->active();
In this case Yii generates parameters automatically and it will be equivalent to this:
SELECT * FROM "customer" WHERE "status"=:qp1
Value 1 will be binded to :qp1 parameter, note that in this case column names are also double quoted.
If you try to use more conditions, params will be :qp2, :qp3 and so on (default PARAM_PREFIX is :qp).
As for your second query, it can be rewritten like this:
$model = Libro::find()
->where([
'tipo' => 'Nacimiento',
'cerrado' => 0,
'anyo' => date('Y'),
])->one();
Such queries look way better and readable in this state.
Yii2 allows generate even more complex conditions in queries, check this section of the docs for more details.
P.S. It's better to use english for naming in your code. Think about other international developers supporting your code. date('Y') can be calculated using database functions depending on used RDBMS.
I am working on a problem where I need to add an OR clause to a set of existing conditions. The current conditions are built in a hash in a method and at the end, they are used in the where clause. Here is a simplified example:
...
conds.merge!({:users => {:archived => false}})
Model.where(conds)
I am trying to add an OR clause to the current set of conditions so it would be something like '(conditions) OR new_condition'. I'd like to add the OR statement without converting each addition to the conds hash into a string. That would be my last option. I was hoping someone has done something like this before (without using Arel). I seem to recall in Rails 2 there was a way to parse a conditions hash using a method from the model (something like Model.some_method(conds) would produce the where clause string. Maybe that would be a good option to just add the OR clause on to that string. Any ideas are appreciated. Thank you for your help!
I found a way to do what I needed. Instead of changing all of the conditions that I am building, I am parsing the conditions to SQL using sanitize_sql_for_conditions. This is a private method in ActiveRecord, so I had to put a method on the model to allow me to access it. Here is my model method:
def self.convert_conditions_hash_to_sql(conditions)
self.sanitize_sql_for_conditions(conditions)
end
So, once I convert my conditions to text, I can add my OR clause (along with the appropriate parentheses) to the end of the original conditions. So, it would go something like this:
Model.where('(?) OR (model.type = ? AND model.id IN(?))', Model.convert_conditions_hash_to_sql(conds), model_type, model_id_array)
After selecting some products a user clicked on proceed button. Now I need to display the selected data on next page. I was successful in getting the id's of selected data using the following code.
String[] array = request.getParameterValues("arrayid");
Now I need to query mysql database using "select * from table where id=?"
I can use this query in a loop. But is there any other or a better way to do this?
Use IN keyword while selecting as select * from table where id IN(comma separated ids)
String[] array = request.getParameterValues("arrayid");
String sql = "SELECT * FROM TABLENAME WHERE id IN ?";
PreparedStatement ps = con.prepareStatement(sql);
ps.setArray(1,con.createArrayOf("CHAR", array));
If your question is how to query for a set of IDs in a table, the other answers correctly refer you to SQL's IN keyword. However if you're asking specifically how to do it in Java, JDBC's PreparedStatement, which is the generally recommended way of executing queries in Java, does not make constructing these IN statements easy. I posted a suggested way to address this issue reasonably cleanly here: Can PreparedStatement.addBatch() be used for SELECT queries?
I want to run a query like this:
SELECT * FROM table WHERE field LIKE '%search_term%'
In CI you can bind parameters to queries, if you used field=? but this does not work for field LIKE "%?%". From debugging output it seems the query used is field LIKE "%'search'%".
Is there an alternative way to do searching in CodeIgniter?
You can use this query:
SELECT * FROM table WHERE field LIKE ?
And bind with %search% instead of search.
You should be aware that this query will be slow in MySQL. You might want to look at free-text search instead (Lucene, Sphinx, or MySQL's built-in free-text search functions).
this is active record class for codeigniter
$this->db->select('*');
$this->db->like('columnname','both');
$query=$this->db->get("tablesname");
$result=$query->result_array();
if(count($result))
{
return $result;
}
else
{
return FALSE;
}
You should try this..I think its help you..
both means %columnname%,
before means %columnname,
after means columnname%
$search_term=$this->input->post('textboxName');
$search_term="%".$search_term."%";
$sql="SELECT * FROM table WHERE field LIKE ? ";
$query=$this->db->query($sql,array($search_term));
$res=$query->result();
what i can understand CI is adding quotes, pass FALSE as third parameter while binding to prevent CI adding quotes.