Dynamically passing of parameter in rails sql query - mysql

Below is an SQL query which fetches some data related to user.
def self.get_user_details(user_id)
result = Event.execute_sql("select replace(substring_index(properties, 'text', -1),'}','') as p, count(*) as count
from ahoy_events e where e.user_id = ?
group by p order by count desc limit 5", :user_id)
return result
end
I want to dynamically pass values to user id to get the result.
I am using the below method to sanitize sql array, but still it returns no result. The query works fine if given static parameter.
def self.execute_sql(*sql_array)
connection.execute(send(:sanitize_sql_array, sql_array))
end
Because the query is complicated I am couldn't figure out the ActiveRecord way to get the results.
Is there any way I could get this sorted out?

I don't know why that should not work. May SQL-Syntac SELECT * FROM users ...
dynamic passing some other way you can do this: "some string #{user.id#ruby code} some more string"
You can do querys in Activerecord like this: User.where(id: user.id).where(field2: value2).group_by(:somevalue).order(:id)

Related

laravel where clause value and column name

How can i do these in laravel query where clause?
select * from table_samples where 1 = id
// basically i can do like where id = 1
select * from table_samples where 1000 > rate
// basically i can do like where rate < 1000
select * from table_samples where 'bogart' = name
// basically i can do like where name = "bogart"
My point is if you interchange the column and value its working on mysql, but if i do this in laravel where clause it doesn't work?
Something like
TableSample::where('1','id')->first();
TableSample::where('1000','>','rate')->first();
TableSample::where('bogart','name')->first();
// throws an error undefined column name 1, 100, and bogart.
// I know laravel . These are the correct query
TableSample::where('id','1')->first();
TableSample::where('rate','<','1000')->first();
TableSample::where('name','bogart')->first();
Is there any where clauses functions in laravel that can accept or determine if you try to interchange the value and column?
You yan use DB::raw() for this.
TableSample::whereRaw('? = id', [1])->first();
Just make sure you use parameter substitution like above to prevent creating sql injection vulnerabilities.
https://laravel.com/docs/5.6/queries#raw-expressions
The whereRaw and orWhereRaw methods can be used to inject a raw where clause into your query
TableSample::whereRaw('1 = id')->first();
https://laravel.com/docs/5.6/queries#raw-methods

how to use as sentence in rails ActiveRecord query interface

For example, how to represent
select id from users as u,teachers as t where u.id = t.id
through the relevant api.
And I want a ActiveRecord::relation object as the result.
You can use it like
sql = "Select id from ... your sql query here"
record= ActiveRecord::Base.connection.execute(sql)

Need to convert an array to Integer for a MySQL query in a Rails API

I have a piece of code which fetches the list of ids of users I follow.
#followed = current_user.followed_user_ids
It gives me a result like this [11,3,24,42]
I need to add these to NOT IN mysql query.
Currently, I am getting NOT IN ([11,3,24,42]) which is throwing an error. I need NOT IN (11,3,24,42)
This is a part of a find_by_sql statement, so using where.not is not possible for me in this point.
In rails 4:
#followed = current_user.followed_user_ids # #followed = [11,3,24,42]
#not_followed = User.where.not(id: #followed)
This should generate something like select * from users where id not in (11,3,24,42)
As you comment, you are using find_by_slq (and that is available in all rails versions). Then you could use the join method:
query = "select * from users where id not in (#{#followed.join(',')})"
This would raise mysql errors if #followed is blank, the resulting query would be
select * from users where id not in ()
To solve this whiout specifiying aditional if statements to your code, you can use:
query = "select * from users where id not in (0#{#followed.join(',')})"
Your normal queries would be like:
select * from users where id not in (01,2,3,4)
but if the array is blank then would result in
select * from users where id not in (0)
which is a still valid sql statement and is delivering no results (which might be the expected situation in your scenario).
you can do something like:
#followed = [11,3,24,42]
User.where('id not in (?)', #followed)

Check if query result is empty

I am performing a query to a database in ruby using Sequel ORM. The query is performed by:
query = "SELECT * FROM albums WHERE artist = 'John';"
DB.fetch(query)
I would like to check whether the result of the query is empty, i.e. if not entry of the DB matches the query conditions.
I could:
empty = true
DB.fetch(query) do |row|
empty = false
end
but I would like to know whether there is a direct method to chek whether the query returns no result.
You want the empty? method:
query = "SELECT * FROM albums WHERE artist = 'John';"
empty = DB.fetch(query).empty?

How to pass data dynamically to mysql query

I have following query,
SELECT t_subject.subject, SUM( t_skilllist.skill_level ) AS total_skill, t_users.first_name,
t_skilllist.skill_level
FROM `t_skilllist`
JOIN t_subject ON t_subject.id = t_skilllist.subject_id
JOIN t_users ON t_users.id = t_skilllist.user_id
WHERE t_subject.subject = 'html'
GROUP BY t_users.first_name
ORDER BY total_skill DESC
LIMIT 0 , 30
I want to display subject and skill level for each student. But, for one subject I can do that with above query. As an example for html it works. However, I want to pass more than one subject to the query dynamically. I tried to combined subjects with AND operator but it return empty result set.
How to solve this? How to pass more than two subjects to the query? I am using PHP as server side scripting language.
You can use the IN() clause.
WHERE t_subject.subject IN ('html', 'php', 'and', 'a', 'lot', 'more')